我正在尝试运行的代码如下。我试图通过小部件框获取用户输入,然后运行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'
答案 0 :(得分:2)
您尝试在bind
类上调用Button
而未实际创建Button
对象(相比之下,您使用Label
正确创建了Label
pack
首先是对象,然后在其上调用Button
)。您需要首先构建bind
,然后然后调用新对象上的"<Button-1>"
。发生错误的原因是您尝试调用方法而不将其绑定到对象,因此第一个位置参数(self
)被解释为Button
,并且当它尝试调用set
方法时在它上面(在这种情况下,unique_ptr
),一切都破了。