19.3Tkinter举例
标签组件
#-*-coding: utf-8-*-
import Tkinter
top = Tkinter.Tk() # 创建顶层窗口
label = Tkinter.Label(top, text="Hello World!") # 创建标签组件
label.pack() # packer管理和显示组件
Tkinter.mainloop() # 进入主事件循环
按钮组件
#-*-coding: utf-8-*-
import Tkinter
top = Tkinter.Tk()
quit = Tkinter.Button(top, text="Hello World!", command=top.quit) # 创建按钮组件。第三个参数就是回调函数对象,按下按钮后,执行回调函数。
quit.pack()
Tkinter.mainloop()
标签和按钮组件
#-*-coding: utf-8-*-
import Tkinter
top = Tkinter.Tk()
hello = Tkinter.Label(top, text="Hello World!")
hello.pack()
quit = Tkinter.Button(top, text="QUIT", command=top.quit, bg="red", fg="white") # bg参数表示按钮组件用红色填充,而fg参数表示其中的文本用白色显示
quit.pack(fill=Tkinter.X, expand=1) # fill参数是让QUIT按钮充满水平方向的剩余空间,expand参数引导packer填充了水平方向的所有可视空间,并将按钮延伸到窗口的左右边界。
Tkinter.mainloop()
#-*-coding: utf-8-*-
# 这一例子中增加了进度条组件,进度条与标签进行交互
from Tkinter import *
def resize(ev=None): # 回调函数,在滑块移动时,激活运行
label.config(font='Helvetica -%d bold' % scale.get())
top = Tk()
top.geometry('250x150') # 限定顶层窗口尺寸为250x150。
label = Label(top, text='Hello World!', font='Helvetica -12 bold')
label.pack(fill=Y, expand=1) # 在竖直方向充满剩余空间,
scale = Scale(top, from_=10, to=40, orient=HORIZONTAL, command=resize) # from_和to两个参数表示进度条范围,orient参数表示进度条的取向,水平放置还是竖直放置,command就是回调函数
scale.set(12) # 设定进度条初始值在12
scale.pack(fill=X, expand=1) # 在水平方向充满剩余空间
quit = Button(top, text='QUIT', command=top.quit, activeforeground='white', activebackground='red') # activeforeground参数表示按钮被按下时,文本的颜色为白色;activebackground参数表示按钮被按下时,按钮背景色变为红色。
quit.pack()
mainloop()
偏函数应用举例
#-*-coding: utf-8-*-
from functools import partial as pto
from Tkinter import Tk, Button, X
from tkMessageBox import showinfo, showwarning, showerror # 这是什么模块?
WARN = 'warn'
CRIT = 'crit'
REGU = 'regu'
SIGNS = {
'do not enter': CRIT,
'railroad crossing': WARN,
'55\nspeed limit': REGU,
'wrong way': CRIT,
'merging traffic': WARN,
'one way': REGU,
}
# 定义危急、警告和通知三个回调函数对象
critCB = lambda: showerror('Error', 'Error Button Pressed!')
warnCB = lambda: showwarning('Warning', 'Warning Button Pressed!')
infoCB = lambda: showinfo('Info', 'Info Button Pressed!')
top = Tk()
top.title('Road Signs')
Button(top, text='QUIT', command=top.quit, bg='red', fg='white').pack()
# 偏函数应用,书上说是“创建按钮类”,这样text就作为参数传入,从而实例化相应的按钮
MyButton = pto(Button, top) # 危急、警告和通知三个回调函数的共同参数?书上是“模板化的按钮类及根窗口top”
# 书上说是再次模板化
CritButton = pto(MyButton, command=critCB, bg='white', fg='red') # 相当于CritButton = Button(top, command=critCB, bg='white', fg='red')?但是缺少text,应该理解为一个函数对象,以text为参数。
WarnButton = pto(MyButton, command=warnCB, bg='goldenrod1')
ReguButton = pto(MyButton, command=infoCB, bg='white')
for eachSign in SIGNS:
signType = SIGNS[eachSign]
cmd = '%sButton(text=%r%s).pack(fill=X, expand=True)' % (signType.title(), eachSign, '.upper()' if signType == CRIT else '.title()') # python求值字符串
eval(cmd)
top.mainloop()