76-闭包的用法

下面的代码用到了《66-偏函数应用:简单的图形窗口》
图形窗口上的按钮有个command选项,其实它就是一个函数。如下:

import tkinter
from functools import partial

def hello():
    lb.config(text="Hello China!")

def welcome():
    lb.config(text="Hello Tedu!")

root = tkinter.Tk()
lb = tkinter.Label(text="Hello world!", font="Times 26")
MyBtn = partial(tkinter.Button, root, fg='white', bg='blue')
b1 = MyBtn(text='Button 1', command=hello)
b2 = MyBtn(text='Button 2', command=welcome)
b3 = MyBtn(text='quit', command=root.quit)
lb.pack()
b1.pack()
b2.pack()
b3.pack()
root.mainloop()

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

import tkinter
from functools import partial

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

root = tkinter.Tk()
lb = tkinter.Label(text="Hello world!", font="Times 26")
MyBtn = partial(tkinter.Button, root, fg='white', bg='blue')
b1 = MyBtn(text='Button 1', command=hello('China'))
b2 = MyBtn(text='Button 2', command=hello('Tedu'))
b3 = MyBtn(text='quit', command=root.quit)
lb.pack()
b1.pack()
b2.pack()
b3.pack()
root.mainloop()
    原文作者:凯茜的老爸
    原文地址: https://www.jianshu.com/p/c2e674c03f24
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞