Set default value for ttk Combobox

I am using Python 3.2.1 on Arch Linux x86_64. It really drives me crazy: I just want to have a default value, a pre-selected value for ttk.Combobox , as soon as I hide it. This is my code:

 from tkinter import Tk, StringVar, ttk root = Tk() def combo(parent): value = StringVar() box = ttk.Combobox(parent, textvariable=value, state='readonly') box['values'] = ('A', 'B', 'C') box.current(0) box.grid(column=0, row=0) combo(root) root.mainloop() 

What draws an empty Combobox . What is funny is that if I do not use the function, it works fine:

 from tkinter import Tk, StringVar, ttk root = Tk() value = StringVar() box = ttk.Combobox(root, textvariable=value, state='readonly') box['values'] = ('A', 'B', 'C') box.current(0) box.grid(column=0, row=0) root.mainloop() 

Of course, in a real program, I need to use a function, so I need a different solution.

+8
python tkinter combobox ttk
source share
3 answers

The problem is that the StringVar instance gets garbage collection. This is because it is a local variable due to the way you wrote your code.

One solution is to use a class so that your StringVar is saved:

 from tkinter import Tk, StringVar, ttk class Application: def __init__(self, parent): self.parent = parent self.combo() def combo(self): self.box_value = StringVar() self.box = ttk.Combobox(self.parent, textvariable=self.box_value, state='readonly') self.box['values'] = ('A', 'B', 'C') self.box.current(0) self.box.grid(column=0, row=0) if __name__ == '__main__': root = Tk() app = Application(root) root.mainloop() 
+23
source share

When your combo function exits, the local value variable will be destroyed. You need a constant variable, such as a global variable or a variable that is a property of the class, so this value does not collect garbage while the widget still exists.

+4
source share

The get() method can be used in your function to rename StringVar and save it under a different name so as not to lose it through garbage collection at all.

 value = StringVar() keepvalue = value.get() 

then use the keepvalue value instead of the value:

 box = ttk.Combobox(root, textvariable=keepvalue, state='readonly') 

For me, it showed "A" in the combo box.

0
source share

All Articles