Python图形界面编程1

偏函数在GUI应用举例

具体内容可以参考Python函数式编程——偏函数(PFA)

偏函数允许预存函数变量并冻结这些预定参数,运行所需的变量再解冻,由这些最终的参数去调用函数

# -*- 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,
    'merging traffic':WARN,
    'one way':REGU,
}

#匿名函数 函数式编程 给3种类型的提示button传参
critCB = lambda: showerror('Error', 'Error Button Pressed!')
warnCB = lambda: showwarning('Warning', 'Warning Button Pressed!')
infoCB = lambda: showinfo('Info', 'Info Button Pressond!')
#顶层界面
top = Tk()
top.title('Road Signs')
Button(top, text='QUIT', command=top.quit, bg='red', fg='white').pack()
#偏函数
MyButton = pto(Button, top)#模板化按钮和top窗口为mybutton
CritButton = pto(MyButton, command=critCB, bg='white', fg='red')#再次模板化MyButton
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()')
    print cmd
    eval(cmd)#eval函数将字符串当成有效Python表达式来求值,并返回计算结果

top.mainloop()

创建的5个cmd字符串:

CritButton(text='do not enter'.upper()).pack(fill=X, expand=True)
WarnButton(text='railroad crossing'.title()).pack(fill=X, expand=True)
ReguButton(text='55\nspeed limit'.title()).pack(fill=X, expand=True)
ReguButton(text='one way'.title()).pack(fill=X, expand=True)
WarnButton(text='merging traffic'.title()).pack(fill=X, expand=True)

这里写图片描述

其他更高级的控件

比如下拉列表,复选框等等具体看文档开发即可。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注