76-内部函数:闭包

图形窗口上的按钮有个command选项,其实它就是一个函数。如下:

import tkinter
from functools import partial

def hello():
    lb.config(text="Nice to meet you!")

def doing():
    lb.config(text="What are you doing!")

root = tkinter.Tk()
lb = tkinter.Label(text = "Hi Cht!",font = "Times 26")
b1 = tkinter.Button(root, fg ='white', bg = 'blue', text = 'Button b1',command = doing)  # 不使用偏函数生成按钮
MyBtn = partial(tkinter.Button, root, fg = 'white', bg = 'blue')  # 使用偏函数定义MyBtn
b2 = MyBtn(text='Button b2',command = hello )
b3 = MyBtn(text='quit', command = root.quit)
lb.pack()
b1.pack()
b2.pack()
b3.pack()
root.mainloop()

结果输出:

 

按下Button 1和Button 2就会执行hello和doing两个函数。这两个函数非常类似,如果有10个按钮,并且都是类似的呢?
换成内部函数、闭包的的语法如下:

import tkinter
from functools import partial

def hello(world):
    def doing():
        lb.config(text="Hello %s!" % world)
    return doing  # hello函数的返回值还是函数

root = tkinter.Tk()
lb = tkinter.Label(text = "Hi Cht!",font = "Times 26")
b1 = tkinter.Button(root, fg ='white', bg = 'blue', text = 'Button b1',command = hello('Cht'))  # 不使用偏函数生成按钮
MyBtn = partial(tkinter.Button, root, fg = 'white', bg = 'blue')  # 使用偏函数定义MyBtn
b2 = MyBtn(text='Button b2',command = hello('Hjp') )
b3 = MyBtn(text='quit', command = root.quit)
lb.pack()
b1.pack()
b2.pack()
b3.pack()
root.mainloop()

 效果一样:

 

posted @ 2019-06-05 20:33  hejp  阅读(163)  评论(0编辑  收藏  举报