为了账号安全,请及时绑定邮箱和手机立即绑定

Tkinter TypeError:“StringVar”类型的参数不可迭代

Tkinter TypeError:“StringVar”类型的参数不可迭代

繁星点点滴滴 2023-10-18 21:01:41
我正在尝试使用 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:


查看完整回答
反对 回复 2023-10-18
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

wordLabel = Label(root, updateLabel(word_guess))

您尝试创建一个新标签Label并使全局wordLabel引用新标签而不是旧标签。即使它工作正常,这也不会更新你的 GUI,因为新标签没有打包。

它中断的原因是,虽然更改了namedupdateLabel的内容并将其返回,但它并没有被用作新标签的。除了指定父窗口小部件之外,您还应该仅对构造函数使用关键字参数,否则该参数的解释可能与您期望的不同。(坦率地说,我很惊讶你竟然能以这种方式调用该函数;我本来期望在调用时出现 a 。)StringVartexttextvariableTypeError

无论如何,您所需要做的就是直接将其添加到新文本中text,因为它也是全局的。.set这将自动更新外观wordLabel(通常刷新显示所需的任何 tkinter 内容的模数) - 这就是StringVar 容器类的要点(而不是仅使用纯字符串)。


查看完整回答
反对 回复 2023-10-18
  • 2 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信