2

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
Cœur
  • 37,241
  • 25
  • 195
  • 267
WRJ
  • 617
  • 3
  • 9
  • 19

1 Answers1

6

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", ""))
Amin Khodamoradi
  • 392
  • 1
  • 6
  • 18
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685