user14279959
user14279959

Reputation:

"UnboundLocalError: local variable 'count' referenced before assignment" when integer variable gets referenced in a function

Whenever I mention a variable(which already exists) in a function, it comes up with this error:

UnboundLocalError: local variable 'count' referenced before assignment

Here is my code:

from tkinter import *
from tkinter.ttk import *
import simpleaudio as sa
main = Tk()
list = ["you yu" , "she hui fa zan" , "bian hua" , "dui yi xie shi" , "you bu tong de kan fa" , "wan quan bu tong" , "chi ... de guan dian" , "qing chun qi" , "you ge xing", "yi zi wo wei zhong xin"]
count = 0
def next():
    if count == 10:
        Label(main, text="You have finished!").pack(side= TOP)
    else:
        Label(main, text= list[count]).pack(side= TOP)
        count = str(count)
        wave_obj = sa.WaveObject.from_wave_file(r"C:\Users\User\Downloads\PyWeb\sounds\\" + count + ".wav")
        count = int(count)
        play_obj = wave_obj.play()
        play_obj.wait_done()
        count += 1
Button(main, text= "next", command= next).pack(side= TOP)
main.mainloop()

I don't see anything wrong with the code, pls help me.

Upvotes: 0

Views: 1472

Answers (2)

Viren Ramani
Viren Ramani

Reputation: 73

You need to move your global keyword down into your function.

count = 0
def next():
    global count

Upvotes: 1

Seth
Seth

Reputation: 2369

next() needs to be specifically told that it's allowed to use the global variable count locally. Add the line global count to the function, so it looks like this:

...
def next():
    global count
    if count == 10:
...

For further information on local vs. global variables, check out this article from tutorialspoint.

Upvotes: 1

Related Questions