+ 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()
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
+ 1
Just declare i inside click function not outside its scope
+ 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()
+ 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