Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python tkinter: Using a "textvariable" in a combobox seems useless

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.

like image 990
tjwrona1992 Avatar asked Apr 08 '26 20:04

tjwrona1992


1 Answers

Since Python has no type safety, you're overwriting the reference to the StringVar object with a string. To set the value, call the set method:

test = StringVar()
country = ttk.Combobox(master, textvariable=test)
#...
test.set("hello")
like image 168
Squall Avatar answered Apr 10 '26 09:04

Squall