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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…