WRJ WRJ - 7 months ago 83
Python Question

Set tkinter Entry default value

I'm developing a script that will build GUIs automatically after reading a python script. I'm having problems in getting the Entry objects that I build to accept a default value.

I pass my method a dictionary (arg) which contains a default value and a variable name.

def create_entry(self,
arg):

if 'default' in arg.keys():
var = StringVar(value=arg['default'])
else:
var = StringVar()
box = ttk.Entry(self.mainframe, textvariable=var)
box.grid(column=1, row=self.num, columnspan=2, sticky=(W, E))
label= ttk.Label(self.mainframe, text=arg['name']).grid(column=0, row=self.num, sticky=E)

return box, label


The thing I can't explain is that a similar method for looking up directories works fine....

def create_askdirectory(self,
arg):

if 'default' in arg.keys():
var = StringVar(value=arg['default'])
else:
var = StringVar()
box = ttk.Entry(self.mainframe, textvariable=var)
box.grid(column=1, row=self.num, columnspan=2, sticky=(W, E))

def askdirectory():
dirname = filedialog.askdirectory()
if dirname:
var.set(dirname)

button = ttk.Button(self.mainframe, text='directory', command=askdirectory).grid(column=0, row=self.num)

return box, button


Any pointer gratefully appreciated.
Cheers!

Answer

ttk widgets are more sensitive to garbage collection than tkinter widgets. Your variables (which you don't actually need) are local variables, so they are getting garbage collected.

The reason that it works in the other code is that the askdirectory function is inside the create_askdirectory function so it is able to see the local variables.

My advice is to not use StringVar -- in this case they are completely unnecessary.

box = ttk.Entry(self.mainframe)
box.insert(0, arg.get("default", "")