首页 > 解决方案 > 不断检查 tkinter 中的文本框

问题描述

我想要 tkinter 中的 Text 标签来不断检查它是否有价值。我希望它处于一个while循环中并在值匹配时退出它。我的代码不起作用。

while user_input != str(ans):

            master = Tk()
            master.title("Math")
            master.geometry('400x400')

            eq = generate_equation(stage=current_stage)
            ans = calc(eq) 
            Label(master=master,text=f"score: {score}").grid(row=0,column=2,sticky=W)
            Label(master=master, text=f"{q_num}: {eq}").grid(row=0,column=0 ,sticky=W)

            inputtxt = tkinter.Text(master=master,height = 5, width = 20)
            inputtxt.grid()
            user_input =str(inputtxt.get(1.0,"end-1c"))

            mainloop()

标签: pythontkinter

解决方案


试试这个:

import tkinter as tk

def check(event:tk.Event=None) -> None:
    if text.get("0.0", "end").strip() == "answer":
        # You can change this to something else:
        text.insert("end", "\n\nCorrect")
        text.config(state="disabled", bg="grey70")

root = tk.Tk()

text = tk.Text(root)
# Each time the user releases a key call `check`
text.bind("<KeyRelease>", check)
text.pack()

root.mainloop()

它绑定到每个KeyRelease并检查文本框中的文本是否等于"answer"。如果是,它会显示"Correct"并锁定文本框,但您可以将其更改为您喜欢的任何内容。

请注意,这是最简单的答案,不考虑您的代码向文本框中添加内容等问题。为此,您将需要像这样更复杂的代码。


推荐阅读