+ 1
Can someone help me with my code
ive been working on a little program using python and tkinter, everytime i click the button its supposed to raise the number then print it in the console. The program runs, but when i click the button it gives me an error saying "local variable 'x' referenced before assignment" here is my code: from tkinter import * root = Tk() x = 5 def printName(event): print(x) x += 1 object_printButton = Button(root, text='Print something') object_printButton.bind('<Button-1>', printName) object_printButton.pack() root.mainloop()
2 Answers
+ 2
Python automatically reads global variables as if they are in the function scope, but it will not reach out to the global context on *writes* unless you deliberately indicate you want the global variable first:
x = 5
def test():
global x
x += 1
test()
edit: here's a ref with some discussion of how Python resolves variables, etc:
https://stackoverflow.com/questions/10360229/python-why-is-global-needed-only-on-assignment-and-not-on-reads
+ 1
thankyou :)) my program works now ^.^