【问题标题】:Python Matplotlib callback function with parametersPython Matplotlib 带参数的回调函数
【发布时间】:2015-04-29 18:47:07
【问题描述】:

在按钮按下的回调函数中,除了'event'之外,还有没有传递更多的参数?例如,在回调函数中,我想知道按钮的文本(本例中为“下一步”)。我该怎么做?

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

fig = plt.figure()
def next(event):
    # I want to print the text label of the button here, which is 'Next'
    pass


axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(next)
plt.show()

【问题讨论】:

    标签: python button matplotlib callback


    【解决方案1】:

    另一个可能更快的解决方案是使用 lambda 函数:

    import matplotlib.pyplot as plt
    from matplotlib.widgets import Button
    
    fig = plt.figure()
    def next(event, text):
        print(text)
        pass
    
    
    axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
    bnext = Button(axnext, 'Next')
    bnext.on_clicked(lambda x: next(x, bnext.label.get_text()))
    plt.show()
    

    【讨论】:

    • 快速、简单、客观。可以接受答案
    【解决方案2】:

    要获得它,您可能需要将事件处理封装在一个类中,如official tutorial

    import matplotlib.pyplot as plt
    from matplotlib.widgets import Button
    
    class ButtonClickProcessor(object):
        def __init__(self, axes, label):
            self.button = Button(axes, label)
            self.button.on_clicked(self.process)
    
        def process(self, event):
            print self.button.label
    
    fig = plt.figure()
    
    axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
    bnext = ButtonClickProcessor(axnext, "Next")
    
    plt.show()
    

    【讨论】:

    • 这对我来说效果很好,但缺少调用外部对象函数的明显方式。对于任何试图在较大数据结构内的绘图中添加按钮的人,这里有另一个提示。我被困在试图让 myObject.function() 在进程内部被调用。简单的方法是将对象作为参数传递给 init 并在 init 中添加一行,如下所示: def __init__(self, axes, label,someObject): self.localCopy=someObject ....
    猜你喜欢
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    相关资源
    最近更新 更多