【问题标题】:tkinter , python , buttonstkinter,python,按钮
【发布时间】:2014-02-20 00:43:54
【问题描述】:

当我想添加一个按钮时

b = Button(app_name,text="..." , command = any_function)

是否可以使用带有参数的函数

b = Button(app_name, text="..." , command = any_function(7))

我试过了

 (...)
 def cash(price):
        global total
        total.set(total.get() + price)

total = IntVar()
total.set(0)

b1 = Button(app,text = "one ",width = 10,command = cash(1))
b1.pack()
b2 = Button(app,text = "two ",width = 10,command = cash(10))
b2.pack()
b3 = Button(app,text = "three ",width = 10,command = cash(100))
b3.pack()
b4 = Button(app,text = "four ",width = 10,command = cash(1000))
b4.pack()

l_total = Label(app,textvariable = total)
l_total.pack()
(...)

但是l_total 在程序运行时(1000+100+10+1)已经是 1111,就像我按下了四个按钮一样,而且这些按钮也没有向 l_total 添加值。我只想知道为什么它不起作用,因为我知道一个解决方案。

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    你写的:

    b = Button(app_name, text="..." , command = any_function(7))
    

    传递函数不是command,它是调用一个函数,然后传递它的结果作为@987654325 @。


    你需要做的是定义一个新函数,当不带参数调用它时,调用any_function(7)。像这样:

    def any_function_7():
        return any_function(7)
    b = Button(app_name, text="..." , command = any_function_7)
    

    或者,使用较短的lambda 语法来定义函数:

    b = Button(app_name, text="..." , command = lambda: any_function(7))
    

    将表达式包装在这样的函数中,然后传递函数,是一种将函数延迟到以后的方法。可能很难理解,但一旦完成,它在所有地方都非常有用。


    另一种看待它的方式是部分应用该函数,它为您提供了一个您可以在以后完成应用的东西。标准库中有一个 partial 函数可以为您执行此操作:

    from functools import partial
    b = Button(app_name, text="..." , command = partial(any_function, 7))
    

    但你也可以自己做:

    def make_any_function_partial(i):
        def wrapped():
            return any_function(i)
        return wrapped
    b = Button(app_name, text="..." , command = make_any_function_partial(7))
    

    然后您会看到这与使用deflambda 的技巧实际上是一样的,再加上另一个技巧:它是一个返回函数的函数。因此,虽然您可能会调用 make_any_function_partial 并将其结果传递给 command,就像您最初的尝试一样,不同之处在于结果本身就是一个函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 2017-07-23
      • 2020-06-19
      • 2013-04-11
      • 2021-07-04
      • 2012-12-02
      • 2016-09-11
      相关资源
      最近更新 更多