【问题标题】:Constantly checking a text box in tkinter不断检查 tkinter 中的文本框
【发布时间】:2021-11-07 00:52:45
【问题描述】:

我想要 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()

【问题讨论】:

  • 为什么不绑定到"<KeyRelease>"?另外你不应该使用while 循环母鸡使用tkinter,除非你知道它会导致什么。

标签: python tkinter


【解决方案1】:

试试这个:

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" 并锁定文本框,但您可以将其更改为您喜欢的任何内容。

请注意,这是最简单的答案,不包括您的代码向文本框中添加内容之类的问题。为此,您将需要更复杂的代码,例如 this

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 2013-06-14
    • 2016-08-06
    • 1970-01-01
    • 2020-10-05
    • 2019-07-10
    • 2010-11-28
    • 2022-07-24
    相关资源
    最近更新 更多