import tkinter as tk import tkinter.ttk as ttk class Example(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) # give invalid entries a red background style = ttk.Style() style.map("TEntry", foreground=[('invalid', "red")]) # style.map("TEntry", selectforeground=[('invalid', "green")]) # More weirdness when uncommented self.entryVar = tk.StringVar() self.entry = ttk.Entry(self, textvariable=self.entryVar) self.button = ttk.Button(self, text="Button") # this label will show the current state, updated # every second. self.label = tk.Label(self, anchor="w") self.after_idle(self.updateLabel) # layout the widgets self.entry.pack(side="top", fill="x") self.button.pack(side="top", fill="x") self.label.pack(side="bottom", fill="x") # add trace on the variable to do custom validation self.entryVar.trace("w", self.validate) # set up bindings to also do the validation when we gain # or lose focus self.entry.bind("", self.validate) self.entry.bind("", self.validate) def updateLabel(self): '''Display the current entry widget state''' state = str(self.entry.state()) self.label.configure(text=state) self.after(1000, self.updateLabel) def validate(self, *args): '''Validate the widget contents''' value = self.entryVar.get() if "invalid" in value: self.entry.state(["invalid"]) else: self.entry.state(["!invalid"]) if __name__ == "__main__": root = tk.Tk() Example(root).pack(fill="both", expand=True) root.mainloop()