我正在嘗試使用 Tkinter 編寫一個模擬 Hangman 游戲的 GUI。到目前為止,我已經(jīng)讓 GUI 創(chuàng)建了一個標簽,該標簽根據(jù)用戶正確猜測的字母進行更新,但終端仍然給出錯誤:“TypeError:‘StringVar’類型的參數(shù)不可迭代”。我已經(jīng)查看了此錯誤的其他解決方案,但無法弄清楚如何解決該問題。它還沒有完成 - 但到目前為止的代碼如下: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 上運行該函數(shù)時出現(xiàn)問題:“wordLabel = Label(root, updateLabel(word_guess))”來重置標簽。關(guān)于如何在 while 循環(huán)迭代后將標簽更新為 word_guess 有什么建議嗎?
2 回答

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

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