簡體   English   中英

Tkinter-AttributeError:“ str”對象沒有屬性“ set”-骰子模擬器

[英]Tkinter - AttributeError: 'str' object has no attribute 'set' - Dice Roll Simulator

我正在嘗試運行的代碼如下。 我正在嘗試通過小部件框獲取用戶輸入,然后運行while循環來模擬骰子滾動。 我收到以下錯誤。

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'

您嘗試在Button類本身上調用bind而不實際創建Button對象(相反,使用Label首先正確地創建了Label對象,然后在其上調用pack )。 您需要先構造一個Button然后在新對象上調用bind 發生您的錯誤是因為您嘗試調用該方法而不將其綁定到對象,因此第一個位置參數( "<Button-1>" )被解釋為self ,並且在嘗試對其調用Button方法時(在這種情況下) ( set ),一切都壞了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM