Tkinter - AttributeError:'str'对象没有属性'set' - Dice Roll Simulator

时间:2018-03-06 01:32:44

标签: python tkinter dice

我正在尝试运行的代码如下。我试图通过小部件框获取用户输入,然后运行while循环来模拟Dice卷。我收到以下错误。

from tkinter import *

from tkinter import ttk

def Dice_roll(event):

    while True:
        x.get()
        if x[0].lower() == 'y':
            m = random.randrange(1, 7)
            if m == 1:
                print("The number on the dice is", m)
            elif m == 2:
                print("The number on the dice is", m)
            elif m == 3:
                print("The number on the dice is", m)
            elif m == 4:
                print("The number on the dice is", m)
            elif m == 5:
                print("The number on the dice is", m)
            elif m == 6:
                print("The number on the dice is", m)
            else:pass

        if x[0].lower() == 'n':
           print("Thank you for playing the game :-)")
           break

x.delete(0, "end")
root = Tk()
x = Entry(root)
x.pack(side=LEFT)

Label(root, text="Want to roll the dice(Yes/No)?").pack(side=TOP)
Button.bind("<Button-1>",Dice_roll)
Button.pack(side=LEFT)

root.mainloop()

错误消息如下:我试图从Button1获取需要传递给Dice_roll函数的输入。这是我第一次尝试使用tkinter模块。我不确定该功能是否适用于字符串值。

**AttributeError**              Traceback (most recent call last)  

<ipython-input-32-ce597da421bf> in <module>()
 45  
 46 Label(root, text="Want to roll the dice(Yes/No)?").pack(side=TOP)  
---> 47 Button.bind("<Button-1>",Dice_roll)  
 48 Button.pack(side=LEFT)  
 49  

~**\Continuum\anaconda3\lib\tkinter\__init__.py in bind**(self, sequence, func, add)  
   1243         of bound events are returned."""  
   1244  
-> 1245         return self._bind(('bind', self._w), sequence, func, add)  
   1246     def unbind(self, sequence, funcid=None):  
   1247         """Unbind for this widget for event SEQUENCE  the  

AttributeError: 'str' object has no attribute '_bind'

1 个答案:

答案 0 :(得分:2)

您尝试在bind类上调用Button而未实际创建Button对象(相比之下,您使用Label正确创建了Label pack首先是对象,然后在其上调用Button)。您需要首先构建bind,然后然后调用新对象上的"<Button-1>"。发生错误的原因是您尝试调用方法而不将其绑定到对象,因此第一个位置参数(self)被解释为Button,并且当它尝试调用set方法时在它上面(在这种情况下,unique_ptr),一切都破了。