我想要检查每个按钮释放的输入,但是我想要比较的输入值是不断变化的。我怎么做才能在"check“函数中传递另一个参数来修复它呢?
def check(event:tkinter.Event=None, ans #<== Won't work) -> None:
if Text.get("0.0", "end").strip() == str(ans):
check_val = True
while True:
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.bind("<KeyRelease>",check)
inputtxt.grid()
if check_val:
score += 10
q_num += 1
if score % 100 == 0:
current_stage += 1
else:
inputtxt.grid()
inputtxt.delete(1.0,END)
user_input = ""
mainloop()发布于 2021-09-10 21:37:50
问题的解决方案(如TheLizzard对该问题的评论中所述)是在将check()绑定到"<KeyRelease>"时使用lambda语句向其传递额外的参数。
注意您是如何在while循环中运行所有代码的:除非您希望窗口一次又一次地弹出,否则这是没有必要的,因为root.mainloop()会为您运行该循环。变量只需要定义一次,除非您要更改它们。因此,您可以删除while循环。
此外,引用前面有或没有"tkinter“的tkinter属性,如tkinter.Text和Label。因为Label和Text都是tkinter模块的一部分,所以您必须同时使用import tkinter和from tkinter import *。通配符导入(使用from module import * )通常是不被鼓励的。只需使用import tkinter,并在tkinter属性前面使用"tkinter“;在本例中,使用tkinter.Label和tkinter.Tk而不是Label和Tk。
下面是您的代码在进行这些更改后的样子:
import tkinter
def check(ans, text, event=None):
if text.get("0.0", "end").strip() == str(ans):
check_val = True
if check_val:
score += 10
q_num += 1
if score % 100 == 0:
current_stage += 1
else:
inputtxt.grid()
inputtxt.delete(1.0,END)
master = tkinter.Tk()
master.title("Math")
master.geometry('400x400')
eq = generate_equation(stage=current_stage)
ans = calc(eq)
tkinter.Label(master=master, text=f"score: {score}").grid(row=0, column=2, sticky=W)
tkinter.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.bind("<KeyRelease>", lambda event, ans=ans, text=inputtxt: check(ans, text))
inputtxt.grid()
user_input = ""
master.mainloop()注意我是如何将if check_val...代码放在check()函数中的。我假设你想要重复检查这个值。如果没有,只需将代码移回原来的位置即可。
另一个变化是:我将inputtext作为参数传递给inputtxt.bind("<KeyRelease>"...行中的check()。这是因为我注意到您试图在一个不存在的Text小部件中获取文本。
https://stackoverflow.com/questions/69135337
复制相似问题