GUI tkinter与偏函数的应用
版本:python3.6
模块:functools,tkinter
在python3.6中,模块名称是tkinter而不是Tkinter,tkMessageBox也由单独的模块整合进了tkinter.messagebox。
借助偏函数锁定参数的功能可以按类‘批量’设置tkinter中的控件,使语句更加简练。
from functools import partial from tkinter import Tk,Button,X, messagebox WARN = 'warn' CRIT = 'crit' REGU = 'regu' SIGNS = { 'do not enter': CRIT, 'railroad':WARN, '55\nspeed limit':REGU, 'wrong way':CRIT, 'merging traffic':WARN, 'one way':REGU, } critCom = lambda: messagebox.showerror('Error','Error Button Pressed!') #需要lambda赋值为函数,否则只是直接执行showerror reguCom = lambda: messagebox.showinfo('Info','Regular Handle, Sit Down!') warnCom = lambda: messagebox.showwarning('Warning','Warning Button Pressed!') top = Tk() top.title('Road Signs') top.geometry('250x300') Button(top,text='QUIT',command = top.quit,bg = 'red', fg = 'white').pack(fill = X , expand = 0) MyButton = partial(Button,top) #第一阶模块化Button CritButton = partial(MyButton,command = critCom, bg = 'white', fg = 'red') #第二阶模块化Button WarnButton = partial(MyButton,command = warnCom, bg = 'goldenrod1') ReguButton = partial(MyButton, command = reguCom, bg = 'white') for eachsign in SIGNS: signtype = SIGNS[eachsign] cmd = '%sButton(text = %r%s).pack(fill = X, expand = 1)'%(signtype.title(),eachsign,'.upper()' if signtype ==CRIT else '.title()') #-r会给字符串加单引号 eval(cmd) #将字符串转换成可以执行的命令语句 top.mainloop()
输出如下: