Python Forum

Full Version: Variable not defined
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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)
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()
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?
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.
Thanks that helps. You are right. I decided to read more about scope and also functions.