【问题标题】:How to replace lambda callback handlers with callable class object callback handlers?如何用可调用的类对象回调处理程序替换 lambda 回调处理程序?
【发布时间】:2020-08-16 15:18:23
【问题描述】:

我的以下问题与 Mark Lutz 第 4 版 Programming Python 的示例 8-10 有关。该示例是关于创建一个简单按钮栏,用于启动对话框演示并在 stdout 中返回这些对话框调用的值。

对话表如下所示:

#dialogTable.py

from tkinter.filedialog     import askopenfilename
from tkinter.colorchooser   import askcolor
from tkinter.messagebox     import askquestion, showerror
from tkinter.simpledialog   import askfloat

demos = {
    'Open': askopenfilename,
    'Color': askcolor,
    'Query': lambda: askquestion('Warning', 'You typed "rm *"\nConfirm?'),
    'Error': lambda: showerror('Error!', "He's dead, Jim"),
    'Input': lambda: askfloat('Entry', 'Enter credit card number')
}

下面的代码创建了按钮栏并使其正常工作。我的问题与这部分有关:

from tkinter import *
from dialogTable import demos       # button callback handlers
from quitter import Quitter         # attach a quit object to me

class Demo(Frame):
    def __init__(self, parent=None, **options):
        Frame.__init__(self, parent)
        self.pack()
        Label(self, text="Basic demos").pack()
        for key in demos:
            func = (lambda key=key: self.printit(key))
            Button(self, text=key, command=func).pack(side=TOP, fill=BOTH)
        Quitter(self).pack(side=TOP, fill=BOTH)

    def printit(self, name):
        print(name, 'returns =>', demos[name]())    # fetch, call, print

if __name__ == '__main__': Demo().mainloop()

Quitter 只是 quit 按钮的一个类。

我的问题是如何重写此代码以使用可调用的类对象 (__call__) 而不是 lambda 来推迟对实际处理程序的调用?

【问题讨论】:

    标签: python python-3.x class oop tkinter


    【解决方案1】:

    好吧,在这种情况下,您可以做一些事情来达到以下效果:

    from tkinter import *
    from dialogTable import demos       # button callback handlers
    from quitter import Quitter         # attach a quit object to me
    
    class Wrapper:
        def __init__(self, func, key):
            self.func = func
            self.key = key
        def __call__(self):
            return self.func(self.key)
    
    class Demo(Frame):
        def __init__(self, parent=None, **options):
            Frame.__init__(self, parent)
            self.pack()
            Label(self, text="Basic demos").pack()
            for key in demos:
                func = Wrapper(self.printit, key)
                Button(self, text=key, command=func).pack(side=TOP, fill=BOTH)
            Quitter(self).pack(side=TOP, fill=BOTH)
    
        def printit(self, name):
            print(name, 'returns =>', demos[name]())    # fetch, call, print
    
    if __name__ == '__main__': Demo().mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2015-04-24
      • 1970-01-01
      • 2023-02-21
      相关资源
      最近更新 更多