【问题标题】:How to invoke a function that has a parameter(s) without using parenthesis in Python如何在 Python 中不使用括号调用具有参数的函数
【发布时间】:2021-02-05 20:08:22
【问题描述】:

我正在用 Python 构建一个数据可视化应用程序,使用 Tkinter 作为 GUI 和数据科学库 Matplotlib、Seaborn、Pandas 和 NumPy 作为后端。

我有以下代码行,其中button["command"] 是 Tkinter 按钮的命令,该按钮分配给函数self.create_analytics_dashboard(button_plots),该函数在按下按钮时创建一个新的 Tkinter 框架。 button plots 参数是一个对象,负责根据按下的按钮显示正确的图。

        button["command"] = self.create_analytics_dashboard(button_plots)

这个问题有 3 个相关的 Tkinter 帧:

  1. main_dashboard
  2. plots_dashboard
  3. analytics_dashboard

前 2 帧仅包含导航到下一帧的按钮,anaylytics_dashboard 帧包含显示实际可视化的按钮。

这些帧的预期顺序如上所示,但是由于我在前面指定 button["command"] 的那一行,程序跳过 plots_dashboard 并从 main_dashboard 直接转到 analytics_dashboard。

但是没有错误消息,如果我删除括号和其中的参数 (button_plots),如下行所示,程序将以正确的顺序显示帧,而不会跳过 plots_dashboard 帧:

        button["command"] = self.create_analytics_dashboard

显然,我尝试过用谷歌搜索它,但所有结果似乎都在谈论带括号和不带括号的调用函数之间的区别或每个函数的目的。 This article 有助于简洁地解释差异:

当我们调用带括号的函数时,函数会被执行并将结果返回给可调用对象。 在另一种情况下,当我们调用不带括号的函数时,会将函数引用发送给可调用对象,而不是执行函数本身。

因此,由于当我不使用括号时该函数按预期工作,即向可调用对象发送函数引用而不是执行函数本身,所以我尝试使用 functools 库中的部分函数来查看它是否可以工作:

        from functools import partial
        ...
        button_command = partial(self.create_analytics_dashboard)
        button["command"] = button_command(button_plots)

不幸的是,没有任何改变。 plots_dashboard 框架仍然像以前一样被跳过。我需要一种将button_plots 作为参数传递的方法,这样它就可以在self.create_analytics_dashboard 函数中使用而不使用括号,因为这只会执行函数而不是发送对可调用对象的函数引用。

如果有另一种方法可以将变量从类中的一个函数传递到 Python 中同一类中的另一个函数,那么这也可以工作。我只需要button_plots 变量以一种或另一种方式在self.create_analytics_dashboard 函数中可用。

为这篇长文道歉,但这一直困扰着我很长时间,所以我试图提供尽可能多的细节。如果问题中的任何内容没有意义,请告诉我。非常感谢任何帮助。

谢谢

【问题讨论】:

  • button_plots是全局变量还是局部变量?
  • @BryanOakley 这是一个局部变量

标签: python matplotlib tkinter


【解决方案1】:

要使用functools.partial,您必须在创建偏函数时包含参数:

button_command = partial(self.create_analytics_dashboard, button_plots)
button["command"] = button_command

或者,更简洁:

button["command"] = partial(self.create_analytics_dashboard, button_plots)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2014-03-14
    相关资源
    最近更新 更多