python - Tkinter 骰子滚筒

标签 python random tkinter

我是编程新手,刚刚接到一项任务,要使用 Tkinter 在 Python 中创建一个骰子滚筒。我完全被这个错误消息难住了:

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()

提前致谢!

最佳答案

roll()中使用global y,因为您有赋值语句并且想要使用全局y:

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

注意:当您进行赋值y = 2时,您将在本地 namespace 中创建新的y(这禁止使用全局y,因为本地y 范围是函数)。

关于python - Tkinter 骰子滚筒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19387752/

相关文章:

python - 使 Vigenére 加密/解密跳过空格

python - 如何解决 python 中嵌套 for 循环的问题?

Python Tkinter 自定义主题

python - Tcl错误: bad window path name (Python)

python - 从 A 列中获取列名,然后将该列的值保存在新的 C 列中

python - 如何使用Scrapy追踪深度为2的链接?

algorithm - 随机数发生器的变化间隔

java - x = (int)(Math.random() * 1) 0 或 1 的概率是多少?

java - 使用随机物体模拟 2 个骰子,直到掷出 2 或 12

python - 导入错误 : cannot import name 'Tk'