tkinter変数のtrace
メソッドを使用すると、変数が変更されたときに実行される関数を設定できます。
def update_bg(*args):
if variableName.get() == "":
label4.config(bg = "SystemButtonFace")
else:
label4.config(bg = "lawngreen")
variableName.trace('w', update_bg)
あなたのアプリケーションはわかりませんが、これは自分のラベルウィジェットを作成するのに理想的な場所のようです。ここに例があります:
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()
ありがとうございます、あなたの答えはヒープを助けました! –