I wrote this code to be a version manager, but it doesn't execute the command changeDir()
. Why?
Asked
Active
Viewed 648 times
-3

IcyTv
- 405
- 4
- 12
-
What do you mean by doesn't execute the command? – Abid Hasan May 13 '17 at 20:32
-
It doesn't print the desired string – IcyTv May 13 '17 at 20:35
-
1Please don't link to off-site code. See [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – Bryan Oakley May 13 '17 at 20:47
1 Answers
1
You forgot to pass a 'name' argument to changeDir
function. And there's no exception because your statement has no effect!
Snippet to represent the problem:
import sys
def exec_smth():
# execution without effect
exec('write_smth')
try:
# execution with exception because of missing argument
exec('write_smth()')
except TypeError as error:
# now we pass an argument
exec('write_smth("I failed because of %s" % error )')
def write_smth(smth):
sys.stdout.write(smth)
exec_smth()
Anyway, outside your __init__
function there're no StringVar
s at all thanks to garbage collector, so your code would fail anyway!
There're even more problems, because you never bind any of your sv{}
to a widget and expect something in return! But ok, let's try to do things with exec
:
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.entries = []
for _ in range(5):
exec('self.sv{} = tk.StringVar()'.format(_))
exec('self.sv{}.trace("w", self.change_sv)'.format(_))
exec('self.entries.append(tk.Entry(self, text="", textvariable=self.sv{}))'.format(_))
for entry in self.entries:
entry.pack()
def change_sv(*args):
# get id of a variable (you can't rely on that (0-9)!)
idx = args[1][-1:]
# get new value
value = getattr(args[0], 'sv{}'.format(idx)).get()
# result
print('Value changed in self.sv%s to %s!' % (idx, value))
app = App()
app.mainloop()
Output:
As you see - we always need a reference to StringVars and I think that option with a list of them is far better!
Note: If you need to pass something to callback function - use a lambda
function! All code tested with Python 3.
Links:

Community
- 1
- 1

CommonSense
- 4,232
- 2
- 14
- 38