Some widgets can be connected directly to application variables by using special options: variable (Radiobutton, Checkbutton, Scale), textvariable (Label, Button, Entry), onvalue, offvalue, and value (Radiobutton). This connection works both ways: if the variable changes for any reason, the widget it's connected to will be updated to reflect the new value. These Tkinter control variables are used like regular Python variables to keep certain values. It's not possible to hand over a regular Python variable to a widget through a variable or textvariable option. The only kinds of variables for which this works are variables that are subclassed from a class called Variable, defined in the Tkinter module.
Tkinter variables are useful because they live on after the widgets they are tied to have been destroyed. It is possible to fetch input values from them long after the widgets has been dismissed.
s1 = tk.StringVar() # Holds a string; default value ""; textvariable has to be used s2 = tk.StringVar(value="word") # set the initial value i1 = tk.IntVar() # Holds an integer; default value 0 i2 = tk.IntVar(value=5) x1 = tk.DoubleVar() # Holds a float; default value 0.0 x2 = tk.DoubleVar(value=3.14) x1.set(1.2) # changing the value of a variable data = x1.get() # reading the current value of a variable b1 = tk.BooleanVar() # Holds a boolean, returns 0 for False and 1 for True b2 = tk.BooleanVar(value=True)
# Using names for tkinter variables. root = tk.Tk() strvar = tk.StringVar(root, name="person") root.setvar(name="person", value="GvR") print(root.getvar(name="person")) strvar.set("Guido") print(strvar.get())
# Using Entry with variables. strvar = tk.StringVar() entry = tk.Entry(root, textvariable=strvar) strvar.set("new string") print(strvar.get())