如何在tkinter中的Entry小部件中等待输入

2024-09-29 01:28:17 发布

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

我想在tkinter做一个测验,我有五个问题。但是,我想等待一个答案被输入到条目小部件。我知道我可能需要一个按钮,但我不知道该怎么做。 到目前为止,我的代码是:

for i in range(5):
        randChoose = random.choice(choose)
        questionLabel = Label(top, text=full[randChoose]).grid(row=0, column=0)
        answerLabel = Label(top, text="Answer:").grid(row=1, column=0)
        answerEntry = Entry(top, borderwidth=5).grid(row=1,column=1)

        if answerEntry.get() == aFull[randChoose]:
            correctLabel = Label(top, text="Correct!",fg="green").grid(row=2,column=0)
            score += 1
            scoreLabel = Label(top, text=f"Your Score is {score}",fg="green").grid(row=2,column=1)
        else:
            wrongLabel = Label(top, text="Incorrect!",fg="red").grid(row=2,column=0)
            scoreLabel = Label(top, text=f"Your Score is {score}",fg="red").grid(row=2,column=1)
        choose.remove(randChoose)

Tags: textyourtopcolumngreenlabelgridrow
1条回答
网友
1楼 · 发布于 2024-09-29 01:28:17

首先,添加一个按钮

button_pressed = StringVar()

这个变量button_pressed将告诉我们按钮是否被按下
(我们将button_pressed设置为StringVar(),以便.set()可以在按钮的命令中更改此变量)

button = Button(app, text="Enter", command=lambda: button_pressed.set("button pressed"))

按下按钮时,它会将变量button_pressed设置为“按钮按下”

button.grid(row=1, column=1)

然后,等待按钮按下

button.wait_variable(button_pressed)

此代码将等待变量button_pressed更改(为任何内容)

最后,检查条目

if answerEntry.get() == aFull[randChoose]:

最终代码应该如下所示:

for i in range(5):
        randChoose = random.choice(choose)
        questionLabel = Label(app, text=full[randChoose]).grid(row=0, column=0)
        answerLabel = Label(app, text="Answer:").grid(row=1, column=0)
        answerEntry = Entry(app, borderwidth=5).grid(row=1,column=1)

        button_pressed = StringVar()
        button = Button(app, text="Enter", command=lambda: button_pressed.set("button pressed"))
        button.grid(row=1, column=1)

        button.wait_variable(button_pressed)

        if answerEntry.get() == aFull[randChoose]:
            correctLabel = Label(app, text="Correct!", fg="green").grid(row=2, column=0)
            score += 1
            scoreLabel = Label(app, text="Your Score is {score}", fg="green").grid(row=2, column=1)
        else:
            wrongLabel = Label(app, text="Incorrect!", fg="red").grid(row=2, column=0)
            scoreLabel = Label(app, text="Your Score is {score}", fg="red").grid(row=2, column=1)
        choose.remove(randChoose)

你可能想破坏这个按钮,所以在下一个问题上,它不会显示2个按钮

button.destroy()

相关问题 更多 >