首页 > 解决方案 > 为什么我不能在标签中更改字体,但在按钮中我可以(Tkinter.ttk)

问题描述

好吧,就像主题一样,为什么我不能使用 ttkbootstrap 更改 Label 中的字体,但在 Buttons 中一切正常?

第二个问题,是否有一些文档列出了我可以在 ttk 样式表中更改的所有内容?例如背景颜色(就像在 ttkbootstrap 中以某种方式完成的那样),因为在我搜索的任何地方,都提到了“回合背景”,它只改变了按钮的“框架”。

这是一个有问题的代码:

import tkinter as tk
from ttkbootstrap import Style as StyleBs
import tkinter.ttk as ttk

cfg = {
"args_label" : {
    "style" : "TLabel",
    "text" : "Label 12345",   
    },
"args_button" : {
    "style" : "TButton",
    "text" : "Button 12345",   
    },
}

if __name__ ==  "__main__" : 
    root = tk.Tk()
    style = StyleBs("darkly")

    style.configure('TButton', font=('Times New Roman', 21), foreground = "red")  # foreground is changed, font too
    style.configure('TLabel', font=('Times New Roman', 21), foreground = "red")   # foreground is changed, but font is not

    button = ttk.Button(root, **cfg["args_button"], ).grid(row=0, column = 0)
    label = ttk.Label(root, **cfg["args_label"], ).grid(row=1, column = 0)
    
    root.mainloop()

标签: pythontkinterfontslabelttk

解决方案


以下代码对我有用,如果您从 tkinter 而不是 ttk.bootstrap 导入 Style,您可能会更轻松。

我不确定为什么按钮和标签文本以及样式名称都在字典中,这对我来说是新的。

通过删除字典并简单地将所需的文本和样式名称放在按钮和标签构建中,它将满足您的要求。

from tkinter import Tk, Button, Label, ttk
from tkinter.ttk import Style

root = Tk()

#Assigning variable to Style import
style = ttk.Style()

#Building Button and Label in window
button = ttk.Button(root, text='Button 12345', style = 'ButtonStyle.TButton').grid(row=0, column = 0)
label = ttk.Label(root, text='Label 12345', style = 'LabelStyle.TLabel').grid(row=1, column = 0)

#Configuring style to be used by window
style.configure('ButtonStyle.TButton', font=('Times New Roman', 21), foreground='red')
style.configure('LabelStyle.TLabel', font = ('Times New Roman', 21), foreground = 'red')

root.mainloop()

推荐阅读