python - 为什么我不能在标签中更改字体,但在按钮中我可以(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()
解决方案
以下代码对我有用,如果您从 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()
推荐阅读
- javascript - 什么 DOM 事件会更新 ReactJS 应用程序以及如何使用纯 Javascript 强制更新
- mongodb - 为什么 mongodb 查询不返回结果
- c# - Unity C#,如何让精灵只移动一次?
- c# - StandardOutput 在 C# 中返回空字符串
- java - 如何根据设备ID保存数据
- python - 如何在for循环中的当前项目之后调用项目
- soap - 在 Java 8 中使用名称空间读取 Soap 响应
- excel - 来自 Outlook 邮件的 PasteSpecial
- python-3.x - 名称“火花”未定义
- fortran - Fortran 子程序不返回值