在不影响其他按钮和更改按钮的默认字体的情况下,仅使特定TTK按钮加粗的最简单方法是什么?
答案 0 :(得分:2)
可能有一种更简单的方法可以做到这一点,但它似乎有效且符合您的标准。它通过创建默认情况下具有粗体文本的自定义ttk.Button
子类来实现,因此不应受其他按钮样式的任何更改影响。
import tkinter as tk
import tkinter.font as tkFont
import tkinter.ttk as ttk
from tkinter import messagebox as tkMessageBox
class BoldButton(ttk.Button):
""" A ttk.Button style with bold text. """
def __init__(self, master=None, **kwargs):
STYLE_NAME = 'Bold.TButton'
if not ttk.Style().configure(STYLE_NAME): # need to define style?
# create copy of default button font attributes
button = tk.Button(None) # dummy button from which to extract default font
font = (tkFont.Font(font=button['font'])).actual() # get settings dict
font['weight'] = 'bold' # modify setting
font = tkFont.Font(**font) # use modified dict to create Font
style = ttk.Style()
style.configure(STYLE_NAME, font=font) # define customized Button style
super().__init__(master, style=STYLE_NAME, **kwargs)
if __name__ == '__main__':
class Application(tk.Frame):
""" Sample usage of BoldButton class. """
def __init__(self, name, master=None):
tk.Frame.__init__(self, master)
self.master.title(name)
self.grid()
self.label = ttk.Label(master, text='Launch missiles?')
self.label.grid(column=0, row=0, columnspan=2)
# use default Button style
self.save_button = ttk.Button(master, text='Proceed', command=self.launch)
self.save_button.grid(column=0, row=1)
# use custom Button style
self.abort_button = BoldButton(master, text='Abort', command=self.quit)
self.abort_button.grid(column=1, row=1)
def launch(self):
tkMessageBox.showinfo('Success', 'Enemy destroyed!')
tk.Tk()
app = Application('War')
app.mainloop()
结果(Windows 7):