Python偏函數實例

目標:python

  1.編寫一個gui,生成按鈕函數

  2.經過偏函數,生成按鈕oop

  3.經過裝飾器,實現按鈕輸出信息功能測試

 

1.使用Tkinter,建立一個按鈕ui

代碼以下:spa

handetiandeMacBook-Pro:~ xkops$ cat button.pycode

#!/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()

•運行代碼,效果以下圖blog

 

2.經過使用偏函數定義按鈕(偏函數定義一些相通部分的內容)utf-8

代碼以下:it

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"

相關文章
相關標籤/搜索