发布时间:2018-06-09 11:00:01编辑:Run阅读(5735)
Tkinter 中其它常用的一些功能
字体使用
改变组件的显示字体
代码:
import tkinter as tk
root = tk.Tk()
# 创建一个 Label
for i in ('Arial',
('Courier New',),
('Comic Sans MS',),
'Fixdsys',
('MS SansSerif',),
('MS Serif',),
'Symbol','System',
('Times New Roman',),
'Verdana'):
tk.Label(root, text='hello sticky', font=i).grid()
root.mainloop()结果:

在 Windows 上测试字体显示,注意字体中包含有空格的字体名称必须指定为 tuple 类型
使用系统已有的字体
Font 来创建字体
代码:
import tkinter as tk # 引入字体模块 import tkinter.font root = tk.Tk() # 创建一个 Label # 指定字体名称、大小、样式 ft = tkinter.font.Font(family='Fixdsys', size=20, weight=tk.font.BOLD) tk.Label(root, text='hello sticky', font=ft).grid() root.mainloop()
结果:

使用tkinter.font.Font 来创建字体
字体创建属性优先级
使用系统已有的字体显示
代码:
import tkinter as tk
# 引入字体模块
import tkinter.font
root = tk.Tk()
# 创建一个 Label
# 指定字体名称、大小、样式
# 名称是系统可使用的字体
ft1 = tkinter.font.Font(family='Fixdsys', size=20, weight=tk.font.BOLD)
tk.Label(root, text='hello sticky', font=ft1).grid()
ft2 = tkinter.font.Font(font=('Fixdsys','10', tk.font.NORMAL), size=40)
tk.Label(root, text='hello sticky', font=ft2).grid()
root.mainloop()结果:

创建字体有 font 等其它属性,如 果 font 指 定 了 ,有几个参数将不再起作用,如:family,size,weight,slant,underline,overstrike, 例子中演示的结果是 ft2中字体大小为10,而不是40
得到字体的属性值
测试 measure 和 metrics 属性
代码:
import tkinter as tk
# 引入字体模块
import tkinter.font
root = tk.Tk()
# 创建一个 Label
ft1 = tkinter.font.Font(family='Fixdsys', size=20, weight=tk.font.BOLD)
tk.Label(root, text='hello font', font=ft1).grid()
ft2 = tkinter.font.Font(font=('Fixdsys','10', tk.font.NORMAL), size=40)
tk.Label(root, text='hello font', font=ft2).grid()
# 得到字体的宽度
print(ft1.measure('hello font'))
print(ft2.measure('hello font'))
# 打印两个字体的属性
for i in ('ascent', 'descent', 'linespace', 'fixed'):
print(ft1.metrics(i))
print(ft2.metrics(i))
root.mainloop()结果:

使用这两个方法得到已创建字体的相关属性值
使用 X Font Descriptor
代码:
import tkinter as tk
root = tk.Tk()
for ft in ('Times', 'Helvetica', 'Courier', 'Symbol',):
tk.Label(root, text='hello font', font=('-*-%s-*-*-*--*-240-*')%(ft)).grid()
root.mainloop()结果:

上一篇: tkinter -- Grid
51114
50505
41121
37966
32434
29335
28207
23051
23019
21341
1378°
2075°
1728°
1657°
1945°
1730°
2403°
4059°
3937°
2808°