在函数中创建一个tkinter按钮,同时使用lambda作为命令,会正常工作吗?

2024-04-27 00:45:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在使用Tkinter创建一个应用程序来实例化GUI。我正在尝试使它面向对象,这样代码可以在其他地方使用,使Tkinter更易于使用。我遇到的问题是能够用按钮命令的参数调用复杂函数

我试着尽可能多地学习纽扣。我已经阅读并观看了关于将命令绑定到特定鼠标单击并使用partial传递函数以分解函数的视频。这些选项不适合当前的代码体系结构。我尝试的最后一个想法是使用lambda创建一个临时函数

def add_button(self, title, command, where, frame):
    button = ttk.Button(frame, text=title,command=lambda: command)
    button.pack(side=where, fill='both', expand=True)
    return button

这是一个用所需小部件实例化页面的类

class StartPage(Page):

    def __init__(self, container, controller):
        super().__init__(container, controller)

        title_frame = tk.LabelFrame(self, text='StartPage')
        title_frame.pack(side='top')
        title = tk.Label(title_frame, text='EPA Engine Report Filing', font=('Helvetica', 16))
        title.pack(side='bottom', pady=25)

        buttons = {'Quit': quit(), 'Stuff': do_something()}

        button_frame = tk.Frame(self)
        button_frame.pack(side='top', pady=75)

        for button, command in buttons.items():
            self.add_button(button, command, 'bottom', button_frame)

我的具体问题是,当for循环遍历StartPage.__init__中声明为按钮的字典时,“Stuff”按钮的lambda函数是否覆盖了前一个“quit”按钮的lambda函数?如果是这种情况,最后创建的按钮将是唯一的按钮工作,如果我理解lambda。运行此代码时,不会显示任何内容。当按钮的函数没有括号时,会出现初始窗口,但按钮不会执行任何操作

感谢您的阅读和任何建议,您可以给是感激的


Tags: lambda函数代码textselftitleinitbutton
1条回答
网友
1楼 · 发布于 2024-04-27 00:45:49

你的代码中有几个问题

首先,使用lambda是不正确的。当您执行lambda: command时,lambda什么也不做。如果希望lambda调用命令,则需要使用括号告诉python执行函数(例如:lambda: command())。但是,如果不传递任何参数,那么lambda本身就没有任何作用。您只需将命令直接绑定到按钮(例如:command=command

另一个问题是您错误地定义了buttons。考虑以下代码:

buttons = {'Quit': quit(), 'Stuff': do_something()}

上述代码在功能上与此相同:

result1 = quit()
result2 = do_something()
buttons = {'Quit': result1, 'Stuff': result2}

在所有情况下,都需要将引用传递给函数。例如,这应该起作用:

buttons = {'Quit': quit, 'Stuff': do_something}
...
def add_button(self, title, command, where, frame):
    button = ttk.Button(frame, text=title,command=command)

相关问题 更多 >