博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
76-内部函数:闭包
阅读量:7086 次
发布时间:2019-06-28

本文共 1290 字,大约阅读时间需要 4 分钟。

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

import tkinterfrom functools import partialdef 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')  # 使用偏函数定义MyBtnb2 = 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 tkinterfrom functools import partialdef 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')  # 使用偏函数定义MyBtnb2 = MyBtn(text='Button b2',command = hello('Hjp') )b3 = MyBtn(text='quit', command = root.quit)lb.pack()b1.pack()b2.pack()b3.pack()root.mainloop()

 效果一样:

 

转载于:https://www.cnblogs.com/hejianping/p/10981803.html

你可能感兴趣的文章
git 搭建多人开发环境
查看>>
ubuntu升级 openssh
查看>>
在上海麦迪广告有限公司 做工作的工作项目
查看>>
【ZZ】互联网协议入门(二)
查看>>
swift遇见的坑 和 第三方库资源
查看>>
get post 区别
查看>>
c:forEach使用索引
查看>>
将Java程序作成exe文件的N种方法
查看>>
Ubuntu 12.04 LTS建立内核树(2)
查看>>
python 之第三方插件安装
查看>>
设置IP地址的技巧
查看>>
android图片文件的路径地址与Uri的相互转换
查看>>
java.security包实现对象加密
查看>>
李学江:B2B行业门户网站最终页标题设置方法
查看>>
心空空的,说不清感觉
查看>>
php版快速排序
查看>>
java数组之间区别
查看>>
cacti install
查看>>
Cisco模拟器GNS3和虚拟机VMware的整合
查看>>
Hyper-v 基本使用方法
查看>>