如何将TTK按钮改为粗体?

2024-05-03 09:52:02 发布

您现在位置:Python中文网/ 问答频道 /正文

在不影响其他按钮和更改按钮的默认字体的情况下,最简单的方法是什么?在


Tags: 方法字体情况按钮
1条回答
网友
1楼 · 发布于 2024-05-03 09:52:02

也许有一种更简单的方法可以做到这一点,但它似乎有效并且符合您的标准。它通过创建一个自定义的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):

screenshot of tkinter window showing a boldface ttk.button

相关问题 更多 >