python等宽字体怎么调_如何将Tkinter小部件设置为等宽的平台独立字体?

在标准字体部分中说

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.")

我得到的是这个:

55e2be967499aaf3f30a203d3ea7c1a7.png

这对我来说看起来不像是等宽的,所以我检查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是怎样的呢?

840Pz.png

上面引用的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")

现在终于得到了一个等宽的结果:

84933066d7fea67de027e5cb983cf2a8.png

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

最佳答案 标准字体(包括TkFixedFont)只能作为普通字符串给出,而不能作为元组.即font =’TkFixedFont’工作,而font =(‘TkFixedFont’,)(请注意括号和逗号)不会.

这似乎是一般情况.我用Tkinter.Button和ttk.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”周围的括号,问题中的代码将完全正常工作.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值