首页 > 编程语言 > 详细

Python偏函数实例

时间:2017-01-09 20:32:12      阅读:260      评论:0      收藏:0      [点我收藏+]

目标:

  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"

 

Python偏函数实例

原文:http://www.cnblogs.com/xkops/p/6266254.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!