在标准字体部分中说
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.")
我得到的是这个:
这对我来说看起来不像是等宽的,所以我检查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是怎样的呢?
上面引用的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")
现在终于得到了一个等宽的结果:
不可否认,我的平台选择的是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”周围的括号,问题中的代码将完全正常工作.