The command I set for a Tkinter button was a function that changed the text of a label. Yet the text does not seem to change!
The variable I attempted to change using the function "textChange()" is called "text", and the purpose of its value is to be the text of a label called "finalText". But, the text of the label "finalText" didn't change!
#Imports
from tkinter import *
#Variables
wn = Tk()
text = 'Button Commands'
#Change Text
def textChange():
global variable
text = 'Can do THIS!'
finalText = Label(wn, text=text)
finalText = Label(wn, text=text)
finalText.place(x=0, y=0)
#Button
btn = Button(wn, command=(textChange()))
btn.place(x=5, y=20)
CodePudding user response:
You actually create a new label and assign to a local variable finalText
inside textChange()
. So the global finalText
is not changed.
You need to use finalText.config(text=text)
to update the text of the global finalText
.
Also command=(textChange())
will execute textChange()
immediately without clicking the button. Use command=textChange
instead.
Below is the updated code:
#Imports
from tkinter import *
#Variables
wn = Tk()
text = 'Button Commands'
#Change Text
def textChange():
text = 'Can do THIS!'
# update the text of the global label finalText
finalText.config(text=text)
finalText = Label(wn, text=text)
finalText.place(x=0, y=0)
#Button
btn = Button(wn, command=textChange)
btn.place(x=5, y=20)
wn.mainloop()