I am trying to make a GUI using tkinter for a app of my. but when I use print on a global variable I get an error that its not defined. Why? (the print is to check the value of the variable) also its have to be a global because I am using it more outside the function. also I tried to change it to message_here = enter_mess_here.get()()
enter_mess = tk.Label(root, text = 'enter below the message')
enter_mess.pack()
enter_mess_here = tk.Entry(root)
enter_mess_here.pack()
def getting_message():
global message_here
message_here = enter_mess_here.get()
done_procces_mess = tk.Label(root, text = "message got procced!")
done_procces_mess.pack()
get_mess = tk.Button(root, text = "procces message", command = getting_message)
get_mess.pack()
print(message_here)
This is because the global variable is only defined when the function is ran. You only pass a reference to the function into tk.Button (that is, the function without () at the end).
For example:
def global_test():
global x
x = 5
y = global_test
print(x)
Outputs NameError: name 'x' is not defined
Whereas:
def global_test():
global x
x = 5
y = global_test()
print(x)
Outputs 5
To use it in Tkinter, I would wrap up the functionality in a class. That way you can run the button and remember the message without using global variables.
import tkinter as tk
class TkinterMessageBox():
def __init__(self):
self.root = tk.Tk()
self.enter_mess = tk.Label(self.root, text = 'enter below the message')
self.enter_mess.pack()
self.enter_mess_here = tk.Entry(self.root)
self.enter_mess_here.pack()
self.get_mess = tk.Button(self.root, text = "procces message", command = self.getting_message)
self.get_mess.pack()
self.root.mainloop()
def getting_message(self):
self.message_here = self.enter_mess_here.get()
done_procces_mess = tk.Label(self.root, text = "message got procced!")
done_procces_mess.pack()
self.root.destroy()
message_box = TkinterMessageBox()
print(message_box.message_here)
Example usage is in the documentation .
Move print(message_here)
into the getting_message
callback function of the button, and remove global message_here
.
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.