Python Matplotlib回调函数带参数

7

在按钮按下的回调函数中,除了 '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()
2个回答

9

另一个可能更快的解决方案是使用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()

快速、简单、客观。可以被接受的答案。 - Gilian

6
为了实现这一点,您可能需要将事件处理封装在一个类中,就像官方教程所示:
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()

这对我很有效,但缺乏调用外部对象函数的明显方法。对于任何试图在较大的数据结构内添加一个按钮到绘图的人,这里有另一个提示。我一直卡在尝试在process内调用myObject.function()上。简单的方法是将对象作为参数传递给init,并在__init__中添加一行代码: def init(self, axes, label,someObject): self.localCopy=someObject .... - Ryan Dorrill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接