2017-02-10 95 views

回答

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)中:

screenshot of tkinter window showing a boldface ttk.button

相關問題