Enviroment:
Python 3.10.3, VSCode, Windows 11
Describing:
I write a program with tkinter by Python.
def examination():
exam = Frame()
exam.pack()
quesinfo = []
quesnumb = 0
def next():
is_right.forget()
nextques.forget()
okayques.grid(column=5, row=2, columnspan=2)
quesnumb += 1
quesinfo.append(core())
question.set(quesinfo[quesnumb][0])
This is just a part of my code, but the problem is here. When I run the program, the interpreter says:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\${MyName}\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "d:\Python\Usable Programs\Auto Maths Questions UI\Main.py", line 102, in next
quesnumb = quesnumb + 1
UnboundLocalError: local variable 'quesnumb' referenced before assignment
You know, quesnumb
is a local variable, so I can't use global
to declare it.
But, that's joking! Look at to the source code again:
quesinfo.append(core())
question.set(quesinfo[quesnumb][0])
It's correct, But why quesnumb += 1
is not?
Fixing and Debugging
I tried my best to fix it.
For testing and dubugging, I replaced quesnumb += 1
to quesnumb = 1
. It ran successfully!
I think, maybe quesnumb
can just reference or assignment? So I replaced it to quesnumb = quesnumb + 1
.
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\${MyName}\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "d:\Python\Usable Programs\Auto Maths Questions UI\Main.py", line 102, in next
quesnumb = quesnumb + 1
UnboundLocalError: local variable 'quesnumb' referenced before assignment
Uh-huh... That's a real Unexpect Wrong...
I must get the answer in time, because I'll use this program on a competition at Sunday (Mar. 27). Winning the competition is all depends on this program. Could you help me to check the problem and find the root cause? Thanks so much!