Tkinter Variable get() and set()
You can use the get( ) method to get the variable content and the set( ) method to set the variable content.
Tkinter Variable get() and set() Example#1
The application of the set() method.
This program can display the string "I like tkinter" if you click the Hit button when executing, or change it to not display the string if it is already displayed.
Line 16 of this program sets the label content to the variable x, line 7 sets the label content to be displayed, and line 10 sets the label content to the empty string to not display the label content.
from tkinter import *
def btn_hit(): # Handling button events
global msg_on # Define global variables
if msg_on == False:
msg_on = True
x.set("I like apidemos.com") # Display text
else:
msg_on = False
x.set("") # No text displayed
root = Tk()
root.title("apidemos.com") # Window Title
msg_on = False # The default for global variables is False
x = StringVar() # Label's variable content
label = Label(root,textvariable=x, # Set Label content to variable x
fg="blue",bg="lightyellow", # Blue letters on light yellow background
font="Verdana 16 bold", # Font settings
width=25,height=2) # Label contents
label.pack()
btn = Button(root,text="Click Me",command=btn_hit)
btn.pack()
root.mainloop()
Output:
After clicking Click Me:
In the above example, the boolean msg_on variable is used to determine if the "I like tkinter" string is to be displayed.
-
If msg_on is False, it means that the "I like tkinter" string is not currently displayed.
-
If msg_on is True, it means that the "I like tkinter" string is currently displayed.
The status of msg_on is changed when the Click Me button is clicked, see line 6 and line 9. The content of the textariable parameter of the label object is also changed by the set() method, line 7 is set to display the "I like tkinter" string and line 10 is set to not display the "I like tkinter " string.
Although the above program works, it does not use another method in this section, get( ), which can get the content of a variable for a parameter of the Widget control, and we will use the following program to improve it.
Tkinter Variable get() and set() Example#2
By eliminating the boolean msg_on variable, we can directly get the current Widget control parameter content from the get( ) method, and then determine whether to display the "I like tkinter" string from that content. The way to determine is to display "I like tkinter" if it is currently an empty string, or to display an empty string if it is not currently an empty string.
from tkinter import *
def btn_hit():
if x.get() == "":
x.set("I like apidemos.com")
else:
x.set("")
root = Tk()
root.title("apidemos.com")
x = StringVar()
label = Label(root,textvariable=x,
fg="blue",bg="lightyellow",
font="Verdana 16 bold",
width=25,height=2)
label.pack()
btn = Button(root,text="Click Me",command=btn_hit)
btn.pack()
root.mainloop()
Output: