更新时间:2023-02-12 09:37:10
我认为正确的方法是对已分配给小部件的 tkinter 变量使用 trace
.
I think the correct method is to use trace
on a tkinter variable that has been assigned to a widget.
例如...
import tkinter
root = tkinter.Tk()
myvar = tkinter.StringVar()
myvar.set('')
mywidget = tkinter.Entry(root,textvariable=myvar,width=10)
mywidget.pack()
def oddblue(a,b,c):
if len(myvar.get())%2 == 0:
mywidget.config(bg='red')
else:
mywidget.config(bg='blue')
mywidget.update_idletasks()
myvar.trace('w',oddblue)
root.mainloop()
跟踪中的 w
告诉 tkinter 每当有人写入(更新)变量时,每次有人在 Entry 小部件中写入内容时都会发生这种情况,请执行 oddblue
.跟踪总是将三个值传递给您列出的任何函数,因此您需要在您的函数中期待它们,因此 a,b,c
.我通常不使用它们,因为无论如何我需要的一切都是在本地定义的.据我所知,a
是变量对象,b
是空白的(不知道为什么),c
是跟踪模式(即w).
The w
in trace tells tkinter whenever somebody writes (updates) the variable, which would happen every time someone wrote something in the Entry widget, do oddblue
. The trace always passes three values to whatever function you've listed, so you'll need to expect them in your function, hence a,b,c
. I usually do nothing with them as everything I need is defined locally anyway. From what I can tell a
is the variable object, b
is blank (not sure why), and c
is the trace mode (i.e.w
).