[英]I'm getting an error that says AttributeError: 'str' object has no attribute 'read' and i do not know how to fix it
[英]I'm getting this error in python: “AttributeError: 'str' object has no attribute 'set'”. I'm using tkinter, how do I fix this?
我正在制作一個簡單的石頭剪刀布游戲,但在這一行中出現錯誤:result.set("")。 單擊按鈕時,此行應清除輸入框。 我該如何解決他的問題?
result = StringVar()
compRandom = random.randint(1, 3)
compPick = compRandom.get()
def reset():
result.set("")
userTake.set("")
Entry(root, text=result, font='arial 10 bold', bg='turquoise2', width=50).place(x=25, y=250)
Button(root, font='arial 13 bold', text='PLAY', padx=5, bg='cornflower blue', command=play).place(x=170, y=190)
Button(root, font='arial 13 bold', text='RESET', padx=5, bg='cornflower blue', command=reset).place(x=90, y=310)
Button(root, font='arial 13 bold', text='EXIT', padx=5, bg='cornflower blue', command=exit).place(x=250, y=310)
root.mainloop()
我得到的錯誤代碼是:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files (x86)\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/57797/PycharmProjects/Tutorial/Tkinter GUI Tutorial/19 - Rock Paper Scissors.py", line 61, in reset
result.set("")
AttributeError: 'str' object has no attribute 'set'
感謝您對更新的評論。 好的,這正是你出錯的地方:
if userPick == compPick:
result = "Draw"
elif userPick == "Rock" and compPick == "Paper":
result = "You lose, the computer chose paper!"
當您最初創建result
變量時,您將其專門設置為 Tkinter 可以使用的StringVar
類型。 但是,當您像在if/else
中那樣直接為它分配字符串值時,它就變成了常規的str
。
現在, StringVar
有一個set()
方法,但str
沒有,這會導致錯誤。 你應該做的是:
if userPick == compPick:
result.set("Draw")
elif userPick == "Rock" and compPick == "Paper":
result.set("You lose, the computer chose paper!")
這會將result
保留為 StringVar 類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.