此代码是泳池记分牌的开始。直到我按下按钮,它才会起作用,然后出现一个回溯,说“分配之前已被引用”。这是完整的代码,尽管您可能不需要全部:
from tkinter import*
import tkinter.messagebox as box
window = Tk()
window.configure(bg = 'white')
frame_stripes = Frame(window, bg = 'white')
frame_spots = Frame(window, bg = 'white')
stripes = 7
spots = 7
stripe_fouls = 0
spot_fouls = 0
def another_go():
box.showinfo('Another Go', 'You get another go')
def foul_2_gos():
box.showinfo('Extra Go', 'Your opponent gets 2 goes')
def stripes_pot():
stripes -= 1
another_go()
stripes_plus = Button(frame_stripes, text = 'Stripes Pot', command = stripes_pot)
def stripes_foul_add():
stripes_fouls += 1
foul_2_goes()
stripes_foul = Button(frame_stripes, text = 'Stripes Foul', command = stripes_foul_add)
def spots_pot():
spots -= 1
another_go()
spots_plus = Button(frame_spots, text = 'Spots Pot', command = spots_pot)
def spots_foul_add():
spots_fouls += 1
foul_2_goes()
spots_foul = Button(frame_spots, text = 'Spots Foul', command = spots_foul_add)
stripes_plus.pack()
spots_plus.pack()
stripes_foul.pack()
spots_foul.pack()
frame_stripes.pack(padx = 30, pady = 30)
frame_spots.pack(padx = 30, pady = 30)
window.mainloop()
回溯如下:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Dylan.DESKTOP-7RLU752\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1702, in __call__
return self.func(*args)
File "C:\Users\Dylan.DESKTOP-7RLU752\Desktop\Pool Score Counter.py", line 26, in stripes_foul_add
stripes_fouls += 1
UnboundLocalError: local variable 'stripes_fouls' referenced before assignment
答案 0 :(得分:1)
您已经在函数之前声明了stripes
,然后在函数内部对其进行了引用,但是在每个函数内部,您必须通过添加{{1}来声明要使用全局变量stripes
。 }。您应该对导致异常的每个变量执行此操作。
global stripes
答案 1 :(得分:1)
由于未指定变量应全局使用而收到错误。您可以通过如下修改功能来实现:
def stripes_pot():
global stripes
stripes -= 1
another_go()
stripes_plus = Button(frame_stripes, text = 'Stripes Pot', command = stripes_pot)
def stripes_foul_add():
global stripes_fouls
stripes_fouls += 1
foul_2_goes()
stripes_foul = Button(frame_stripes, text = 'Stripes Foul', command = stripes_foul_add)
def spots_pot():
global spots
spots -= 1
another_go()
spots_plus = Button(frame_spots, text = 'Spots Pot', command = spots_pot)
def spots_foul_add():
global spots_fouls
spots_fouls += 1
foul_2_goes()
spots_foul = Button(frame_spots, text = 'Spots Foul', command = spots_foul_add)
也就是说,使用全局变量并不总是一个好主意。对于您的项目,基于类的实现会更好。