Python偏函数实例

目标:

  1.编写一个gui,生成按钮

  2.通过偏函数,生成按钮

  3.通过装饰器,实现按钮输出信息功能

 

1.使用Tkinter,创建一个按钮

代码如下:

handetiandeMacBook-Pro:~ xkops$ cat button.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import Tkinter
#定义一个窗口
root = Tkinter.Tk()
#定义一个按钮
b1 = Tkinter.Button(root, foreground='white', background='blue', text='Button1')

#包装
b1.pack()

root.mainloop()

•运行代码,效果如下图

 

2.通过使用偏函数定义按钮(偏函数定义一些相通部分的内容)

代码如下:

handetiandeMacBook-Pro:~ xkops$ cat button.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import Tkinter
from functools import partial

root = Tkinter.Tk()
#使用偏函数定义相同的内容
MyButton = partial(Tkinter.Button, root, foreground='white', background='blue')

b1 = Tkinter.Button(root, foreground='white', background='blue', text='Button1')
b2 = MyButton(text='Button2')
b3 = MyButton(text='Button3')
b4 = MyButton(text='quit')

b1.pack()
b2.pack()
b3.pack()
b4.pack()

root.mainloop()

•运行代码,测试效果

 

3.定义函数,实现点击button2按钮,输出"Hello,world"功能,点击quit按钮,关闭窗口功能。

代码如下:

handetiandeMacBook-Pro:~ xkops$ cat button.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import Tkinter
from functools import partial

def greet():
    print "Hello, world"
root = Tkinter.Tk()

MyButton = partial(Tkinter.Button, root, foreground='white', background='blue')

b1 = Tkinter.Button(root, foreground='white', background='blue', text='Button1')
b2 = MyButton(text='Button2', command=greet)
b3 = MyButton(text='Button3')
b4 = MyButton(text='quit', command=root.quit)

b1.pack()
b2.pack()
b3.pack()
b4.pack()

root.mainloop()

•运行代码,点击Button2和quit按钮查看效果

 

4.通过编写装饰器实现,点击不同按钮,打印不同的信息。

代码如下:

handetiandeMacBook-Pro:~ xkops$ cat button.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import Tkinter
from functools import partial

def greet(word):
    def welcome():
        print "Hello, %s" % word
    return welcome

root = Tkinter.Tk()

MyButton = partial(Tkinter.Button, root, foreground='white', background='blue')

b1 = Tkinter.Button(root, foreground='white', background='blue', text='Button1')
b2 = MyButton(text='Button2', command=greet('world'))
b3 = MyButton(text='Button3', command=greet('Python'))
b4 = MyButton(text='quit', command=root.quit)

b1.pack()
b2.pack()
b3.pack()
b4.pack()

root.mainloop()

•运行代码,测试效果,点击Button2,后台输出"Hello, world", 点击Button3后台输出"Hello, Python"

 

posted @ 2017-01-09 18:42  xkops  阅读(624)  评论(1编辑  收藏  举报