Tkinter TypeError:类型为“StringVar”的参数不可iterable

2024-10-02 02:31:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用Tkinter编写一个GUI来模拟刽子手游戏。到目前为止,我已经让GUI创建了一个标签,该标签根据用户正确猜测的字母进行更新,但终端仍然给出了一个错误:“TypeError:type'StringVar'的参数不可iterable”。我已经研究了这个错误的其他解决方案,但还没有找到解决问题的方法

它还没有完成-但以下是到目前为止的代码:

import randomword
# from PyDictionary import PyDictionary
from 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 text


mainloop()

当我在wordLabel上运行函数:“wordLabel=Label(root,updateLabel(word_guess))”以重置标签时,就会出现问题。关于如何在while循环迭代之后将标签更新为word_guess,有什么建议吗


Tags: textconfignotroot标签resultwordguess
2条回答
wordLabel = Label(root, updateLabel(word_guess))

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

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

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

此行导致错误:

wordLabel = Label(root, updateLabel(word_guess))

你想得太多了。应该是这样的:

updateLabel(word_guess)

这里还有一个主要错误。这一行:

while incorrect > 0:

将导致您的程序锁定。您需要将其更改为:

if incorrect > 0:

相关问题 更多 >

    热门问题