繁体   English   中英

Tkinter如何将TTK按钮更改为粗体?

[英]Tkinter how to change TTK button to bold?

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

可能有一种更简单的方法来执行此操作,但它似乎有效并且符合您的标准。 它通过创建一个自定义的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):

tkinter窗口的屏幕截图,其中显示了粗体字ttk.button

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM