python - 不断检查 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()
解决方案
试试这个:
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"
并锁定文本框,但您可以将其更改为您喜欢的任何内容。
请注意,这是最简单的答案,不考虑您的代码向文本框中添加内容等问题。为此,您将需要像这样更复杂的代码。
推荐阅读
- javascript - 隐藏元素上的动画可见
- java - 使用递归的子串
- reactjs - 如何将对象设置为状态变量?
- php - Dompdf 写在其他 html 元素之上 - Laravel 6 - PHP 8
- flutter - 即使 Firebase 身份验证有错误,我的颤振应用程序也会移动到新页面
- php - laravel中如何统计数据的数量
- javascript - 打字稿:映射对象值,同时保持可选键可选
- android - 为什么在 EditText 的开头有额外的空间
- python - 如何使用 Python 从本地文件创建数据 url?
- javascript - 如何在浏览器/标签关闭时发送 API 请求?