python - 如何更改选项卡标题框的大小和 ttk 笔记本选项卡的字体?

标签 python python-3.x tkinter ttk

我想在 ttk.notebook python 3x 中更改选项卡标题的字体、宽度和高度

通过下面的代码,我可以更改选项卡标题框的宽度

text=f'{"frame 1": ^30s}

但是如何更改“第 1 帧”的字体以及选项卡标题框的高度?
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
notebook = ttk.Notebook(root)

f1 = tk.Frame(notebook, bg='red', width=200, height=200)
f2 = tk.Frame(notebook, bg='blue', width=200, height=200)

notebook.add(f1, text=f'{"frame 1": ^30s}')
notebook.add(f2, text=f'{"frame 2 longer": ^30s}')

notebook.grid(row=0, column=0, sticky="nw")
root.mainloop()

最佳答案

基于此 answer关于如何自定义 Notebook 的 Tab 配置,您可以像这样将字体信息附加到创建的主题中,以获得您想要的字体类型:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

s = ttk.Style()
s.theme_create( "MyStyle", parent="alt", settings={
        "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } },
        "TNotebook.Tab": {"configure": {"padding": [100, 10],
                                        "font" : ('URW Gothic L', '11', 'bold')},}})
s.theme_use("MyStyle")

notebook = ttk.Notebook(root)

f1 = tk.Frame(notebook, bg='red', width=200, height=200)
f2 = tk.Frame(notebook, bg='blue', width=200, height=200)

notebook.add(f1, text="frame 1" )
notebook.add(f2, text="frame 2 longer" )

notebook.grid(row=0, column=0, sticky="nw")
root.mainloop()

另一种方法是直接配置 Notebook 的 Tab 样式。见下面的代码。
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

s = ttk.Style()
s.configure('TNotebook.Tab', font=('URW Gothic L','11','bold') )

notebook = ttk.Notebook(root)

f1 = tk.Frame(notebook, bg='red', width=200, height=200)
f2 = tk.Frame(notebook, bg='blue', width=200, height=200)

notebook.add(f1, text="frame 1" )
notebook.add(f2, text="frame 2 longer" )

notebook.grid(row=0, column=0, sticky="nw")
root.mainloop()

您必须注意使用之间的区别s.configure('TNotebook.Tab', font=('URW Gothic L','11','bold') )s.configure('TNotebook', font=('URW Gothic L','11','bold') ) .前者更改 Notebook 的 Tab 小部件的字体,而后者更改 Notebook 的字体。

如果您要配置选项卡的许多方面,则使用第一种方法。如果您只想更改 Notebook Tab 的字体,则使用第二种方法。

使用 s.configure('.', font=('URW Gothic L','11','bold') )意味着所有 ttk 小部件字体将是相同的类型。如果这是您想要的,请执行此操作。

关于python - 如何更改选项卡标题框的大小和 ttk 笔记本选项卡的字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54211530/

相关文章:

python - Tensorflow ctc_loss_calculator : No valid path found

python - 如何更改 tkinter 中每个排序算法步骤的颜色

python tkinter 列表框 : adding items

python - 为什么我不能在 python2.7 中解码 ‘utf8’ 字符串?

python - 在命令行中启动脚本时导入模块

python - 是否有一种干净的方法可以将仅 Python 3 的功能添加到 2.7 中使用其他功能的类?

python-3.x - 使用比例更新Python中进度条的颜色?

python - 如何从 python 检查是否安装了任意程序

python - 我如何在 python 中的文件的特定列中写入一些值/字符串

python - 在 python 中使用 key 对 csv 文件进行哈希处理