偏函式應用舉例:路燈指示牌
1 #!/usr/bin/env python 2 # _*_coding:utf-8_*_ 3 # 紅綠燈練習:按照指示型別建立適當當景、背景色的路燈指示牌 4 from functools import partial as pto 5 from tkinter import Tk, Button,X 6 from tkinter.messagebox import showinfo,showwarning,showerror 7 WARN = `warn` 8 CRIT = `crit` 9 REGU = `regu` 10 11 SIGNS = { 12 `do not enter`:CRIT, 13 `railroad crossing`:WARN, 14 `55 speed limit`:REGU, 15 `wrong way`: CRIT, 16 `merging traffic`: WARN, 17 `one way`: REGU, 18 } 19 20 critCB = lambda: showerror(`Error`,`Error Button Pressed!`) 21 warnCB = lambda: showwarning(`Warning`,`Warning Button Pressed!`) 22 infoCB = lambda: showinfo(`Info`,`Info Button Pressed!`) 23 24 25 root = Tk() 26 root.geometry(`800x400`) 27 root.title(`Road Signs`) 28 Button(root,text=`QUIT`,command=root.quit,bg=`red`,fg=`white`).pack() 29 30 31 MyButton = pto(Button,root) 32 CritButton = pto(MyButton,command=critCB,bg=`white`,fg=`red`) 33 WarnButton = pto(MyButton,command = warnCB,bg = `goldenrod1`) 34 ReguButton = pto(MyButton,command = infoCB,bg = `white`) 35 36 for eachSign in SIGNS: 37 signType = SIGNS[eachSign] 38 cmd = `%sButton(text = %r%s).pack(fill = X,expand = True)` %( 39 signType.title(),eachSign,`.upper()` if signType == CRIT else `.title()` 40 ) 41 eval(cmd) 42 43 root.mainloop()