简单的蟒蛇tkinter骰子滚动游戏

时间:2014-11-02 13:37:03

标签: python tkinter

我正在尝试使用tkinter创建一个简单的骰子模拟器,但仍然遇到此错误:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\NetBeansProjects\DiceSIMULATOR\src\dicesimulator.py", line 18, in      <module>
    Label("Enter your guess").pack()
  File "C:\Python34\lib\tkinter\__init__.py", line 2573, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Python34\lib\tkinter\__init__.py", line 2084, in __init__
    BaseWidget._setup(self, master, cnf)
  File "C:\Python34\lib\tkinter\__init__.py", line 2062, in _setup
    self.tk = master.tk
AttributeError: 'str' object has no attribute 'tk'

这是我的代码:

from random import randrange
from tkinter import *


def checkAnswer():
    dice = randrange(1,7)
    if int(guess) == dice:
        tkMessageBox.showinfo("Well Done!","Correct!")
    if int(guess) > 6:
        tkMessageBox.showinfo("Error"," Invalid number: try again")
    elif int(guess) <= 0:
        tkMessageBox.showinfo("Error"," Invalid number: try again")
    else:
        tkMessageBox.showinfo("Incorrect","Incorrect: dice rolled {}.".format(diceRoll))

root = Tk()

Label("Enter your guess").pack()

g = StringVar()
inputGuess = TextBox(master, textvariable=v).pack()
guess = v.get()

submit = Button("Roll Dice", command = checkAnswer).pack()
root.mainloop()

1 个答案:

答案 0 :(得分:1)

以下是代码的修改版本:

Label小部件需要父级(在这种情况下,它是root)。你没有指明这一点。这同样适用于Button小部件。其次,变量v未定义,但我认为您的意思是g,因此将对变量v的所有引用更改为g

from random import randrange
from tkinter import *


def checkAnswer():
    dice = randrange(1,7)
    if int(guess) == dice:
        tkMessageBox.showinfo("Well Done!","Correct!")
    if int(guess) > 6:
        tkMessageBox.showinfo("Error"," Invalid number: try again")
    elif int(guess) <= 0:
        tkMessageBox.showinfo("Error"," Invalid number: try again")
    else:
        tkMessageBox.showinfo("Incorrect","Incorrect: dice rolled {}.".format(diceRoll))

root = Tk()

Label(root,text="Enter your guess").pack() #parent wasn't specified, added root

g = StringVar() 
inputGuess = Entry(root, textvariable=g).pack() #changed variable from v to g
guess = g.get() #changed variable from v to g

submit = Button(root, text = "Roll Dice", command = checkAnswer).pack() #added root as parent
root.mainloop()