• 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()

     效果一样:

  • 相关阅读:
    Vue
    数组去重、数组中的对象去重
    Vue 拖拽组件 vuedraggable 、 vue-dragging 、awe-dnd
    如何衡量一个人的 JavaScript 水平?
    八个免费的Vue图标库
    vue中使用animate.css实现动画
    web本地存储(localStorage、sessionStorage)
    vue引入iconfont报错
    RESTful API 最佳实践
    mysql 用户管理和权限设置
  • 原文地址:https://www.cnblogs.com/hejianping/p/10981803.html
Copyright © 2020-2023  润新知