我正在嘗試使用 Tkinter 編寫一個模擬 Hangman 游戲的 GUI。到目前為止,我已經讓 GUI 創建了一個標簽,該標簽根據用戶正確猜測的字母進行更新,但終端仍然給出錯誤:“TypeError:‘StringVar’類型的參數不可迭代”。我已經查看了此錯誤的其他解決方案,但無法弄清楚如何解決該問題。它還沒有完成 - 但到目前為止的代碼如下:import randomword# from PyDictionary import PyDictionaryfrom tkinter import *root = Tk()playerWord: str = randomword.get_random_word()word_guess: str = ''guesses = ''def returnEntry(arg=None): global word_guess global guesses global wordLabel word_guess = '' # dictionary = PyDictionary() failed = 0 incorrect = 10 result = myEntry.get() while incorrect > 0: if not result.isalpha(): resultLabel.config(text="that's not a letter") elif len(result) != 1: resultLabel.config(text="that's not a letter") else: resultLabel.config(text=result) assert isinstance(END, object) myEntry.delete(0, END) guesses += result for char in playerWord: if char in guesses: # Print the letter they guessed word_guess += char elif char not in guesses: # Print "_" for every letter they haven't guessed word_guess += "_ " failed += 1 if guesses[len(guesses) - 1] not in playerWord: resultLabel.config(text="wrong") incorrect -= 1 wordLabel = Label(root, updateLabel(word_guess)) myEntry.delete(0, END)resultLabel = Label(root, text="")resultLabel.pack(fill=X)myEntry = Entry(root, width=20)myEntry.focus()myEntry.bind("<Return>", returnEntry)myEntry.pack()text = StringVar()text.set("your word is: " + ("_ " * len(playerWord)))wordLabel = Label(root, textvariable=text)wordLabel.pack()def updateLabel(word): text.set("your word is: " + word) return textmainloop()當我在 wordLabel 上運行該函數時出現問題:“wordLabel = Label(root, updateLabel(word_guess))”來重置標簽。關于如何在 while 循環迭代后將標簽更新為 word_guess 有什么建議嗎?
2 回答

函數式編程
TA貢獻1807條經驗 獲得超9個贊
此行導致錯誤:
wordLabel = Label(root, updateLabel(word_guess))
你想多了。應該很簡單:
updateLabel(word_guess)
你那里還有另一個重大錯誤。這行:
while incorrect > 0:
會導致你的程序鎖定。您需要將其更改為:
if incorrect > 0:

肥皂起泡泡
TA貢獻1829條經驗 獲得超6個贊
wordLabel = Label(root, updateLabel(word_guess))
您嘗試創建一個新標簽Label
并使全局wordLabel
引用新標簽而不是舊標簽。即使它工作正常,這也不會更新你的 GUI,因為新標簽沒有打包。
它中斷的原因是,雖然更改了namedupdateLabel
的內容并將其返回,但它并沒有被用作新標簽的。除了指定父窗口小部件之外,您還應該僅對構造函數使用關鍵字參數,否則該參數的解釋可能與您期望的不同。(坦率地說,我很驚訝你竟然能以這種方式調用該函數;我本來期望在調用時出現 a 。)StringVar
text
textvariable
TypeError
無論如何,您所需要做的就是直接將其添加到新文本中text
,因為它也是全局的。.set
這將自動更新外觀wordLabel
(通常刷新顯示所需的任何 tkinter 內容的模數) - 這就是StringVar 容器類的要點(而不是僅使用純字符串)。
添加回答
舉報
0/150
提交
取消