Using the textvariable
attribute when creating a combobox in tkinter seems completely useless. Can someone please explain what the purpose is? I looked in the Tcl documentation and it says textvariable
is used to set a default value, but it looks like in tkinter you would just use the .set
method to do that.
Example showing what I mean:
This doesn't work...
from Tkinter import *
import ttk
master = Tk()
test = StringVar()
country = ttk.Combobox(master, textvariable=test)
country['values'] = ('USA', 'Canada', 'Australia')
country.pack()
# This does not set a default value...
test="hello"
mainloop()
This does work.
from Tkinter import *
import ttk
master = Tk()
country = ttk.Combobox(master)
country['values'] = ('USA', 'Canada', 'Australia')
country.pack()
# This does set a default value.
country.set("hello")
mainloop()
If you are supposed to just use the .set
and .get
methods, what is the point of assigning anything to textvariable
? Every example online seems to use textvariable
, but why? It seems completely pointless.
Under normal circumstances there is no reason to use a StringVar
. I have no idea why most tutorials show it. It adds overhead but provides no extra value. As you observe, you can directly get and set the value of the combobox via the combobox object itself.
The advantage to using a StringVar
comes when you want to either a) have two widgets share the same variable so that one is updated when the other is changed, or b) attach one or more traces to the StringVar
. Both of those are uncommon, but are sometimes quite useful.