I am trying to find the best font for displaying utf-8 characters in a tk.Text.
I let python print all the family names known to tk using this code:
print(font.families(root=self.parent))
and all the known names for usages using this code:
print(font.names(root=self.parent))
However the output out the families is a list of fonts, which have names consisting of one or more words. It's easy to set the ones with one word like this:
text = tk.Text(master=self.frame)
text.configure(font='helvetica 12')
But when I try the same with the font names, which consist of multiple words, I get an error:
_tkinter.TclError: expected integer but got
I can't style it, since it is a tk and not a ttk widget, so unfortunately I cannot do:
style.configure('My.TText', fontsize=12, font='')
I also tried to simply remove whitespace of the family name like this:
text.configure(font='fangsongti')
But that causes tkinter to use some fallback font. I checked it entering a name like:
text.configure(font='fangsongtisdngfjsbrgkrkjgbkl')
print(text.cget('font'))
And this results in printing the exact string I entered as a family name. So it simply accepts everything, except multiple worded names.
I found some fonts, which do look OK, but only at certain sizes and I am not sure if they're available on most systems:
# helvetica 12
# gothic 13
# mincho 13
How can I set fonts with names consisting of multiple words? If I can't, which font, having a one worded name, is appropriate for displaying utf-8 characters like for example Chinese (but not exclusively!) characters on common font sizes and is available on most systems?
解决方案
When specifying fonts in this manner, use a tuple:
text.configure(font=("Times New Roman", 12, "bold"))
Even better, you can create your own custom font objects and specify the attributes by name. Note: before you can create a font object you must first create a root window.
# python 2
# import Tkinter as tk
# from tkFont import Font
# python 3
import tkinter as tk
from tkinter.font import Font
root = tk.Tk()
text = tk.Text(root)
...
myFont = Font(family="Times New Roman", size=12)
text.configure(font=myFont)
The advantage to creating your own fonts is that you can later change any attribute of the font, and every widget that uses that font will automatically be updated.
myFont.configure(size=14)