+ 1

python error

tried making simple program in tkinter. i get UnboundLocalError: local variable 'i' referenced before assignment error when i click the button from tkinter import * window = Tk() i = 1 def click(): hellolbl = Label(window, text="Hello") hellolbl.grid(row=i, column=1) i += 1 but = Button(window, text = "Here we go", command = click) but.grid(row=0, column=0) window.mainloop()

3rd Nov 2020, 2:21 PM
ItzNekS
ItzNekS - avatar
4 Answers
+ 1
Try to add `global i` below the function head `def click()`. As I understand, variables from outside function are read-only until you specify 'global'. def click(): global i # rest of function body here
3rd Nov 2020, 2:33 PM
Ipang
+ 1
Just declare i inside click function not outside its scope
3rd Nov 2020, 2:31 PM
HBhZ_C
HBhZ_C - avatar
+ 1
from tkinter import * window = Tk() i = 1 def click(): global i hellolbl = Label(window, text="Hello") hellolbl.grid(row=i, column=1) i += 1 but = Button(window, text = "Here we go", command = click) but.grid(row=0, column=0) window.mainloop()
3rd Nov 2020, 2:42 PM
Shadoff
Shadoff - avatar
+ 1
thank you for answering everyone HBhZ_C if i put it inside the function, the i would always be 1 when calling grid function so it wouldnt help
3rd Nov 2020, 3:20 PM
ItzNekS
ItzNekS - avatar