Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

python - I am trying to make a GUI for a app I am working on but when I try print a global variable I get an error. Why?

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)
question from:https://stackoverflow.com/questions/65853408/i-am-trying-to-make-a-gui-for-a-app-i-am-working-on-but-when-i-try-print-a-globa

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...