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

问题描述 投票:-1回答:1

我正在尝试运行的代码如下。我试图通过小部件框获取用户输入,然后运行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'
python tkinter dice
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.