代码之家  ›  专栏  ›  技术社区  ›  Martin Kunze

Python:在函数上的matplotlib按钮中添加可选参数

  •  0
  • Martin Kunze  · 技术社区  · 4 年前

    import matplotlib.pyplot as plt
    from matplotlib.widgets import Button
    
    def clicked(event):
        print("Button pressed")
    
    button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
    b1 = Button(button_pos, 'Button1')
    b1.on_clicked(clicked)
    button_pos = plt.axes([0.2, 0.8, 0.1, 0.075])
    b2 = Button(button_pos, 'Button2')
    b2.on_clicked(clicked)
    plt.show()
    

    import matplotlib.pyplot as plt
    from matplotlib.widgets import Button
    
    def clicked(event, text):
        print("Button pressed"+text)
    
    
    button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
    b1 = Button(button_pos, 'Button1')
    b1.on_clicked(clicked(text=" its the first"))
    button_pos = plt.axes([0.2, 0.8, 0.1, 0.075])
    b2 = Button(button_pos, 'Button2')
    b2.on_clicked(clicked)
    b2.on_clicked(clicked(text=" its the second"))
    plt.show()
    

    但通过该更改,我得到以下错误消息:

    Traceback (most recent call last):
      File "/bla/main.py", line 24, in <module>
        b1.on_clicked(clicked(text=" its the first"))
    TypeError: clicked() missing 1 required positional argument: 'event'
    

    它们是在这样一个函数中放入第二个参数的一种方式,还是在Python中需要在这种情况下生成两个单击的函数?

    1 回复  |  直到 4 年前
        1
  •  1
  •   gioxc88    4 年前

    第二个代码的问题是您正在调用函数 clicked 当你在里面用的时候 b1.on_clicked

    相反 b1.点击 将函数作为参数,然后在后台调用该函数,并将事件作为参数传递。

    你可以这样做

    def fn_maker(text=''):
        def clicked(event):
            print(f"Button pressed{text}")
        return clicked
    
    button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
    b1 = Button(button_pos, 'Button1')
    b1.on_clicked(fn_maker(text=" its the first"))
    ...