gpt4 book ai didi

python - 如何将 Tkinter 小部件设置为等宽、平台无关的字体​​?

转载 作者:太空宇宙 更新时间:2023-11-03 11:41:32 26 4
gpt4 key购买 nike

据说here标准字体部分:

Particularly for more-or-less standard user interface elements, each platform defines specific fonts that should be used. Tk encapsulates many of these into a standard set of fonts that are always available, and of course the standard widgets use these fonts. This helps abstract away platform differences.

然后在预定义的字体列表中有:

TkFixedFont A standard fixed-width font.

这也符合我在这里找到的关于在 Tkinter 中选择等宽、平台独立字体的标准方法,例如 this answer 中所述.

唉,当我尝试自己做这个时,就像下面的简单代码一样:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
frame = ttk.Frame(root)
style = ttk.Style()
style.configure("Fixed.TButton", font=("TkFixedFont", 16))

button = ttk.Button(text="Some monospaced text, hopefully", style="Fixed.TButton")
frame.grid()
button.grid(sticky="news")
button.configure(text="I don't quite like this font.")

我得到的是这样的:

TkFixedFont, size 16

这对我来说看起来不像是等宽的,所以我检查了 Tkinter 在我的平台上将 TkFixedFont 翻译成什么:

from tkinter import font
font.nametofont("TkFixedFont").actual()

答案是:

{'family': 'DejaVu Sans Mono', 'size': 9, 'weight': 'normal', 'slant': 'roman', 'underline': 0, 'overstrike': 0}

那么 DejaVu Sans Mono 是什么样子的?

DejaVu Sans Mono, size 16

上面引用的 Tkdocs.com 教程 还有一个关于命名字体 的部分,它说:

the names Courier, Times, and Helvetica are guaranteed to be supported (and mapped to an appropriate monospaced, serif, or sans-serif font)

所以我尝试:

style.configure("Courier.TButton", font=("Courier", 16))
button.configure(style="Courier.TButton")

现在我终于得到了等宽结果:

enter image description here

不可否认,我的平台选择作为标准等宽字体的是 Courier New 而不是 DejaVu Sans Mono,但这至少是某种东西,对吗?但是 TkFixedFont 不应该正常工作吗?

最佳答案

标准字体(包括TkFixedFont)只能作为纯字符串给出,不能作为元组给出。 IE。 font='TkFixedFont' 有效,而 font=('TkFixedFont',)(注意括号和逗号)不会。

这似乎是一般情况。我用 Tkinter.Buttonttk.Style 都试过了。

对于样式,这意味着:

import Tkinter
import ttk

# will use the default (non-monospaced) font
broken = ttk.Style()
broken.configure('Broken.TButton', font=('TkFixedFont', 16))

# will work but use Courier or something resembling it
courier = ttk.Style()
courier.configure('Courier.TButton', font=('Courier', 16))

# will work nicely and use the system default monospace font
fixed = ttk.Style()
fixed.configure('Fixed.TButton', font='TkFixedFont')

经测试可在 Linux 和 Windows 上使用 Python 2.7。

最重要的是,如果只删除 "TkFixedFont" 周围的括号,问题中的代码将完美运行。

关于python - 如何将 Tkinter 小部件设置为等宽、平台无关的字体​​?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48731746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com