2013-10-15 84 views
1

我是新手編程,剛剛被設置爲使用Tkinter在Python中創建一個骰子滾輪。我完全被這個錯誤消息難住:Tkinter骰子滾輪

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__ 
    return self.func(*args) 
    File "C:/Users/d/Desktop/Dice Simulator/Simulator.py", line 12, in roll 
    if y == 1: 
UnboundLocalError: local variable 'y' referenced before assignment 

任何人都可以闡明我的錯誤嗎?這裏是我的整個代碼:

y = 1 
print "Please wait for the GUI to load" 
from Tkinter import * 
DICE = dict(
    sixsided={'name': 'Six Sided Dice', 
       'side': 6}, 
    eightsided = {'name': 'Eight Sided Dice', 
        'side': 8} 
    ) 
names = ['Six Sided Dice', 'Eight Sided Dice'] 
import random 


def back_(): 
    diceroll.destroy() 

def roll(): 
    if y == 1: 
     blankanswer.pack_forget() 
     droll.set("You rolled a " + str(random.randrange(1,endnum,1))) 
     filledanswer.pack() 
     y = 2 
    if y == 2: 
     droll.set("You rolled a " + str(random.randrange(1,endnum,1))) 

def cont_(): 
    y = 1 
    if dice.get() == "Six Sided Dice": 
     selecteddice = "sixsided" 
    if dice.get() == "Eight Sided Dice": 
     selecteddice = "eightsided" 

    diceroll = Tk() 
    diceroll.title("Dice Simulator") 

    endnum = int(DICE[selecteddice]["side"]) 

    droll = StringVar() 
    droll.set("You rolled a " + str(random.randrange(1,endnum,1))) 

    reroll = Button(diceroll, text="Click to roll the " + dice.get() + ".",command=roll) 
    reroll.pack() 

    blankanswer = Label(diceroll, text="You rolled a ") 
    blankanswer.pack() 


    filledanswer = Label(diceroll, textvariable=droll) 

    back = Button(diceroll, text="Back", command=back_) 
    back.pack(side=BOTTOM) 

    diceroll.mainloop() 



diceselect = Tk() 
diceselect.title("Select your dice") 

Label(diceselect, text="Please select the dice you would like to roll").pack() 

dice = StringVar() 
dice.set("Six Sided Dice") 

entry = OptionMenu(diceselect, dice, *names) 
entry.configure(width=15) 
entry.pack(side=LEFT) 

cont = Button(diceselect, text="Continue", command=cont_) 
cont.configure(width=15) 
cont.pack(side=RIGHT) 

diceselect.mainloop() 

在此先感謝!

+0

閱讀消息'UnboundLocalError:本地變量'y'在賦值之前被引用'嘗試解釋器是什麼意思。 –

回答

2

roll()使用global y你有賦值語句,並希望利用全球y

def roll(): 
    global y 
    if y == 1: 
    # other code 

注意:當你做任務y = 2你在當地namesapce創造新y(禁止使用全局y因爲地方y範圍是功能)。