您可以使用tkinter變量的trace
方法來設置函數,以便在變量發生變化時運行。
def update_bg(*args):
if variableName.get() == "":
label4.config(bg = "SystemButtonFace")
else:
label4.config(bg = "lawngreen")
variableName.trace('w', update_bg)
我不知道您的應用程序,但這看起來像是製作您自己的Label小部件的理想場所。這裏有一個例子:
import tkinter as tk
class DuffettLabel(tk.Label):
'''A special type of label that changes the background color when empty'''
def __init__(self, master=None, **kwargs):
tk.Label.__init__(self, master, **kwargs)
self.variable = kwargs.get('textvariable')
if self.variable is not None:
self.variable.trace('w', self.update_bg)
self.update_bg()
def update_bg(self, *args):
if self.variable.get() == "":
self.config(bg = "red")
else:
self.config(bg = "lawngreen")
root = tk.Tk()
root.geometry('200x200')
variableName = tk.StringVar()
ent = tk.Entry(root, textvariable=variableName)
ent.pack()
lbl = DuffettLabel(root, textvariable=variableName)
lbl.pack(fill=tk.X)
root.mainloop()
謝謝,你的答案幫助堆! –