代码如下:
"""导入模块"""
from functools import partial as pto; #偏函数模块
from tkinter import Tk,Button,X; #GUI控件模块
from tkinter.messagebox import showinfo,showwarning,showerror;#GUI消息模块
WARN='warn';#警告类型路牌![在这里插入图片描述](https://img-blog.csdnimg.cn/20200210224027536.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTk1OTg1,size_16,color_FFFFFF,t_70)
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, #单程
}
"""lambda匿名函数"""
critCB=lambda:showerror('Error','Error Button Pressed');
warnCB=lambda:showwarning('Warning','Warning Button Pressed!');
infoCB=lambda:showinfo('Info','Info Button Pressed!');
"""生成GUI对象"""
top=Tk();
top.title('Road Signs');
Button(top,text='QUIT',command=top.quit,bg='red',fg='white').pack();
"""偏函数"""
MyButton=pto(Button,top);
CritButton=pto(MyButton,command=critCB,bg='white',fg='red');
WarnButton=pto(MyButton,command=warnCB,bg='gold');
ReguButton=pto(MyButton,command=infoCB,bg='white');
"""字典遍历"""
for key,value in SIGNS.items():
cmd='%sButton(text=%r%s).pack(fill=X,expand=True)'%(value.title(),key,'.upper()' if value==CRIT else '.title()');
eval(cmd);
top.mainloop();
运行结果
鼠标点击黄色按钮:
鼠标点击白色按钮:
鼠标点击红色字体按钮:
开发环境:Visual Studio 2017 Python 3.6
参考书籍:《Python核心编程》