2014-11-02 177 views
0

我試圖創建一個Tkinter的一個簡單的骰子模擬器,但繼續運行這個錯誤:簡單的Python 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

下面是修改後的版本您的代碼:

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

它是做什麼的 – 2014-11-02 13:41:40

+0

沒有爲'Label'小部件指定父項。 – Kidus 2014-11-02 13:42:57

+0

不要只是轉儲代碼,不要解釋OP出錯的原因。 – 2014-11-02 13:45:28