pythontkinter设置界面字体样式,tkinter - 如何设置字体的文本?

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值