Can Tkinter Styles Be Extended Or Combined?
Let's say I have a style for a button. import Tkinter as tk import ttk root = tk.Tk() ttk.Style(root).configure('Border.TButton', borderwidth=4, relief='raised') I want another s
Solution 1:
Question:
tkinter.Style
be extended or combined?
- Define your own
class Style
by inheriting fromclass ttk.Style
. - Overload method
.configure(...
to implementextend=
.- Save every
kwargs=
options into the instance attributeself._style
. - On argument
extend=
, pre.configure(...
using the options saved inself._style[...]
. - Forward to the original
ttk.Style.configure(...
.
- Save every
import tkinter as tk
import tkinter.ttk as ttk
classStyle(ttk.Style):
EXTENDS = 'extends'def__init__(self, parent):
super().__init__(parent)
self._style = {}
defconfigure(self, cls, **kwargs):
self._style.setdefault(cls, {}).update(kwargs)
extends = self._style.get(kwargs.get(Style.EXTENDS), {})
super().configure(cls, **extends)
super().configure(cls, **kwargs)
Usage:
Note: To change only the font size, use
None
:font=(None, ...
.
class App(tk.Tk):
def __init__(self):
super().__init__()
buttonbox = tk.Frame(self)
buttonbox.grid(row=0, column=0)
style = Style(self)
style.theme_use('clam')
style.configure('Border.TButton',
font=('Helvetica', 10), borderwidth=4, relief='raised')
style.configure('BorderBigFont.TButton',
font=(None, 24),
extends='Border.TButton')
style.configure('BorderRed.TButton',
bordercolor='red',
extends='Border.TButton')
for _style in ['Border.TButton', 'BorderBigFont.TButton', 'BorderRed.TButton']:
btn = ttk.Button(buttonbox, text=_style, style=_style)
btn.grid()
if __name__ == "__main__":
App().mainloop()
Tested with Python: 3.5 - 'TclVersion': 8.6 'TkVersion': 8.6
Post a Comment for "Can Tkinter Styles Be Extended Or Combined?"