1 """Sample demo showing widget states and some font styling.""" 2 import ttk 3 4 states = ['active', 'disabled', 'focus', 'pressed', 'selected', 5 'background', 'readonly', 'alternate', 'invalid'] 6 7 for state in states[:]: 8 states.append("!" + state) 9 10 def reset_state(widget): 11 nostate = states[len(states) // 2:] 12 widget.state(nostate) 13 14 class App(ttk.Frame): 15 def __init__(self, title=None): 16 ttk.Frame.__init__(self, borderwidth=6) 17 self.master.title(title) 18 19 self.style = ttk.Style() 20 21 # get default font size and family 22 btn_font = self.style.lookup("TButton", "font") 23 fsize = str(self.tk.eval("font configure %s -size" % btn_font)) 24 self.font_family = self.tk.eval("font configure %s -family" % btn_font) 25 if ' ' in self.font_family: 26 self.font_family = '{%s}' % self.font_family 27 self.fsize_prefix = fsize[0] if fsize[0] == '-' else '' 28 self.base_fsize = int(fsize[1 if fsize[0] == '-' else 0:]) 29 30 # a list to hold all the widgets that will have their states changed 31 self.update_widgets = [] 32 33 self._setup_widgets() 34 35 def _set_font(self, extra=0): 36 self.style.configure("TButton", font="%s %s%d" % (self.font_family, 37 self.fsize_prefix, self.base_fsize + extra)) 38 39 def _new_state(self, widget, newtext): 40 widget = self.nametowidget(widget) 41 42 if not newtext: 43 goodstates = ["disabled"] 44 font_extra = 0 45 else: 46 # set widget state according to what has been entered in the entry 47 newstates = set(newtext.split()) # eliminate duplicates 48 49 # keep only the valid states 50 goodstates = [state for state in newstates if state in states] 51 # define a new font size based on amount of states 52 font_extra = 2 * len(goodstates) 53 54 # set new widget state 55 for widget in self.update_widgets: 56 reset_state(widget) # remove any previous state from the widget 57 widget.state(goodstates) 58 59 # update Ttk Button font size 60 self._set_font(font_extra) 61 return 1 62 63 def _setup_widgets(self): 64 btn = ttk.Button(self, text='Enter states and watch') 65 66 entry = ttk.Entry(self, cursor='xterm', validate="key") 67 entry['validatecommand'] = (self.register(self._new_state), '%W', '%P') 68 entry.focus() 69 70 self.update_widgets.append(btn) 71 entry.validate() 72 73 entry.pack(fill='x', padx=6) 74 btn.pack(side='left', pady=6, padx=6, anchor='n') 75 self.pack(fill='both', expand=1) 76 77 78 def main(): 79 app = App("Widget State Tester") 80 app.mainloop() 81 82 if __name__ == "__main__": 83 main() 84