Why can’t Tkinter execute a 'simple command'?

Asked

Viewed 253 times

0

I would like to understand why in the code below the tikinter (I think this is the problem) can not execute something simple like 'c = c + 1' ?

Code:

from tkinter import *
import pygame.mixer
sounds = pygame.mixer
sounds.init()
c = 0
e = 0
t = 0

def wait_finish(channel):
    while channel.get_busy():
        pass
def correct():
    s2 = sounds.Sound("correct.wav")
    wait_finish(s2.play())
    c = c + 1
def wrong():
    s4 = sounds.Sound("wrong.wav")
    wait_finish(s4.play())
    e = e + 1
def finish():
    print("Respostas certas: ", c)
    print("Respostas erradas: ",e)

interface = Tk()
interface.title("TVN-Perguntas e respostas")
interface.geometry('550x200+200+100')
b1 = Button(interface, text = "Resposta Certa", width = 10, command = correct)
b1.pack(side = 'left', padx = 10, pady = 10)
b2 = Button(interface, text = "Resposta Errada", width = 10, command = wrong)
b2.pack(side = 'right', padx = 10, pady = 10)
b3 = Button(interface, text = "Sem mais perguntas", width = 20, command = finish)
b3.pack(side = 'bottom', padx = 10, pady = 10)
pergunta = Label(text = "Pergunta:")
pergunta.pack()

interface.mainloop()

Error message:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
    return self.func(*args)
  File "TVN-gui.py", line 15, in correct
c = c + 1
UnboundLocalError: local variable 'c' referenced before assignment

1 answer

2


To make changes to a global variable you must put the keyword global in front of the variable inside the function, thus:

def correct():
    global c
    ...
    c = c + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.