Python Forum
Variable not defined - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Variable not defined (/thread-28223.html)



Variable not defined - Heyjoe - Jul-10-2020

Dear Python Users,

The following program creates a command button. I defined a function called ans1 to give to the command button. It assigns the number 44 to the variable AnswerSelected. When I click on the command button it prints 44. However, at the end of the program it it supposed to print AnswerSelected. At this point it tells me that AnswerSelected is not defined.

What I am trying to do is use command buttons to assign numbers to variables. Any help would be appreciated.

#Create a button widget
from tkinter import *
root = Tk()

def ans1():
    AnswerSelected = 44
    print (AnswerSelected)

Answer1 =Button(root,text="Click me", padx=50, pady=50, bg ="red", command =ans1)
Answer1.grid( row =5, column = 5)
root.mainloop()
print (AnswerSelected)



RE: Variable not defined - menator01 - Jul-10-2020

Prints in the console for me. If you want it to print in a label then you will have to let it know to.
from tkinter import *
root = Tk()

def ans1():
    AnswerSelected = 44
    label['text'] = AnswerSelected
    print (AnswerSelected)

label = Label(root)
label.grid(column=5, row=4)

Answer1 =Button(root,text="Click me", padx=50, pady=50, bg ="red", command =ans1)
Answer1.grid( row =5, column = 5)
root.mainloop()



RE: Variable not defined - Heyjoe - Jul-10-2020

I should have explained my question better. My question is why does AnswerSelected not have a value when it gets to the end of the program?


RE: Variable not defined - ndc85430 - Jul-10-2020

Because it's local to the ans1 function. You need to read about scope. It's also a good idea to avoid global scope for variables if you can.


RE: Variable not defined - Heyjoe - Jul-10-2020

Thanks that helps. You are right. I decided to read more about scope and also functions.