Home > front end >  I keep getting name 'message' not defined in python even though I made it a global variabl
I keep getting name 'message' not defined in python even though I made it a global variabl

Time:12-02

Code(python):

import tkinter as tk
root = tk.Tk()
root.geometry("600x400")
message_var2 = tk.StringVar()


def page2(message):
    print(f'test\n{message}')


def getInputtemp():
    global message
    message = message_var2.get()
    message_var2.set("")


message_entryi = tk.Entry(root, textvariable=message_var2, font=('calibre', 10, 'normal'))
message_entryi.pack()

save_btn2 = tk.Button(root, text='Send', command=getInputtemp)
save_btn2.pack()

if message in ['1886', '2022']:
    page2(message)
root.mainloop()

I want to use the variable 'message' outside of the function but it keeps giving me the not defined error

Even though I made it a global variable and I'm calling the function before trying to use it I still get the error, Even though after making it global and calling it worked in the past with other things its not working here am I doing something wrong? Did I forget some small tiny detail?

CodePudding user response:

The problem that you have, is the usage of the global keyword.

The thing is that, you use global even tho the value doesn't exists in the global scope.

If you want your program to work, the best thing to do is to define message at the start of the program as None, with that process, message exists in the global scope with a value of None.

...
root.geometry("600x400")
message_var2 = tk.StringVar()
message = None # <<<<<<<<<<

def page2(message):
    print(f'test\n{message}')
...

Related:

CodePudding user response:

The issue you have here is that your function getInputtemp is not getting fired. It only gets fired when button save_btn2 is clicked. Also, the if statement where the error is occuring will only get fired once. To fix this, you can either do what @Tkirishima have suggested.

Or just move the if statement inside the getInputtemp function.

def getInputtemp():
    #global message 
    #Then you would no longer need message as a global variable
    message = message_var2.get()
    message_var2.set("")
    if message in ['1886', '2022']:
        page2(message)

But, if you do want the if statement outside the function (which I wouldn't recommend as stated earlier that it would execute when you start the script and never again):

getInputtemp() #The function is called to create message as global variable
if message in ['1886', '2022']:
    page2(message)
  • Related