如何更改标签标题框的大小和ttk笔记本标签的字体?

发布于 2021-01-29 15:03:10

我想在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()
关注者
0
被浏览
135
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    基于有关如何自定义笔记本标签的配置的答案,您可以将字体信息附加到创建的主题中,如下所示,以获取所需的字体类型:

    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()
    

    另一种方法是直接配置笔记本的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') )。前者更改笔记本的Tab小部件的字体,而后者更改笔记本的字体。

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

    使用s.configure('.', font=('URW Gothic L','11','bold') )表示所有ttk小部件字体都属于同一类型。如果这是您想要的,请执行此操作。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看