【问题标题】:Multiple variations of TKInter fontsTKInter 字体的多种变体
【发布时间】:2021-09-08 06:40:01
【问题描述】:

我正在努力更好地理解在tkinterttk 中使用字体。

我的计划是为标题设置两种不同的样式,每种样式都有自己的字体大小。我使用nametofont() 创建了一个字体实例,然后将大小设置为两种不同的样式:

labelFont = tkinter.font.nametofont('TkTextFont')
labelFont.config(weight='bold')

ttk.Style().configure("TLabel", font=labelFont, size=12)
ttk.Style().configure("heading.TLabel", font=labelFont, size=48)

然后将样式应用于标题:

heading = ttk.Label(root, text="Heading", style="heading.TLabel")
label = ttk.Label(root, text="Label", style="TLabel")   #   is style redundant?

不幸的是,我没有得到两种不同的尺寸,所以这显然是错误的方法。

我也试过这样的:

labelFont = tkinter.font.nametofont('TkTextFont')
headingFont = tkinter.font.nametofont('TkTextFont')
# etc

认为我会得到两个独立的字体实例,但它们似乎是同一个实例。如果它们是独立的,我可以使用configure() 为它们每个人指定自己的字体大小。

我采用这种方法是因为我想使用内置的命名字体,并使用变量来保持一致性。正确的做法是什么?

【问题讨论】:

    标签: python-3.x tkinter fonts ttk


    【解决方案1】:

    您需要在Font 的不同实例上使用.config(size=...)

    labelFont = tkinter.font.nametofont('TkTextFont')
    labelFont.config(weight='bold', size=12)
    
    # create a clone of labelFont using Font.copy()
    headingFont = labelFont.copy()
    headingFont.config(size=48)
    
    s = ttk.Style()
    s.configure('TLabel', font=labelFont) # apply to all instance of ttk.Label
    s.configure('heading.TLabel', font=headingFont, size=96)
    
    heading = ttk.Label(root, text='Heading', style='heading.TLabel')
    label = ttk.Label(root, text='Label') # style='TLabel' is not necessary
    

    【讨论】:

    • 为我修复它的是表达式labelFont.copy()。我现在应该知道我应该克隆字体对象。如果您愿意将其添加到您的答案中,我可以接受。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 2021-11-16
    • 2011-02-16
    相关资源
    最近更新 更多