zoukankan      html  css  js  c++  java
  • 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()

     效果一样:

  • 相关阅读:
    鸟哥私房菜*基础篇(3)
    Java 基于Graphics2D绘制电子收据图片
    微信扫码支付沙盒测试,解决沙盒环境下签名验证失败
    JAVA对象合集,根据条件过滤
    java对象根据字段进行排序
    vue 弹窗调用父窗口函数
    php使用post功能,调用微信推送服务
    JS字符串截取
    关于两个 IQueryable 合并
    bootstrap清除数据源
  • 原文地址:https://www.cnblogs.com/hejianping/p/10981803.html
Copyright © 2011-2022 走看看