简体   繁体   中英

Tkinter update label with variable from inside function

I'm using Tkinter to create a window with an entry field and a button. When the button is pressed and a certain condition is not met, I need my_label2 to show a specific text, in this case 'Not Valid'. Otherwise, I need the my_label2 to be blank. I have the variable label_text inside a function that is called by the button press, but I get an error saying that label_text is not defined. Can someone help me out with this?

root = tk.Tk()

def my_function():

valid = #this variable is either true or false

     if valid :
          label_text = ''

     else :
          label_text = 'Not Valid'

my_label = tk.Label(root, text = "Enter text: ")
my_label.grid(row = 0, column = 0)

my_entry = tk.Entry(root)
my_entry.grid(row = 0, column = 1)

my_button = tk.Button(root, text = "Submit", command = my_function)
my_button.grid(row = 1, column = 1)

my_label2 = tk.Label(root, textvariable = label_text)
my_label2.grid(row = 2, column = 1)

root.mainloop()

Tkinter Variables are different from normal variables. To create one:

label_text = tk.StringVar()

Then, rather than assigning to the variable, you nee to use the set method:

label_text.set('')

or

label_text.set('Not Valid')

See: http://effbot.org/tkinterbook/variable.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM