python - 函数内的 matplotlib 按钮单击处理程序不起作用

标签 python matplotlib

如果我在函数内定义按钮单击处理程序,它就不起作用。在下面的示例中,f1 和 f2 看起来相同,但只有当我按下 f2 上的按钮时,它才会产生输出。

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

def handler(*args, **kwargs):
    print('handled')

def testfn():
    f1 = plt.figure('f1')
    b1 = Button(f1.add_axes([0.4, 0.3, 0.1, 0.04]), 'Click!')
    b1.on_clicked(handler)

f2 = plt.figure('f2')
b2 = Button(f2.add_axes([0.4, 0.3, 0.1, 0.04]), 'Click!')
b2.on_clicked(handler)

testfn()

plt.show()

最佳答案

作为the documentation讲述任何小部件,

For the button to remain responsive you must keep a reference to it.

因此您需要从函数返回按钮以保留对它的引用 (button = testfn()),否则函数返回后它将立即被垃圾回收。

这个例子可能看起来像这样:

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

def handler(*args, **kwargs):
    print('handled')

def testfn():
    f1 = plt.figure('f1')
    b1 = Button(f1.add_axes([0.4, 0.3, 0.1, 0.04]), 'Click!')
    b1.on_clicked(handler)
    return b1

f2 = plt.figure('f2')
b2 = Button(f2.add_axes([0.4, 0.3, 0.1, 0.04]), 'Click!')
b2.on_clicked(handler)

button = testfn()

plt.show()

关于python - 函数内的 matplotlib 按钮单击处理程序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48564891/

相关文章:

python - Pandas 中 transpose() 和 .T 的区别

python - 在条形图中绘制列表列表的两个 y 轴

python - 在 matplotlib 中绘制字符串值

python - 向右移动第三个 y 轴

python - 显示拜耳格式图像的像素

python - 我将如何在 Dask 中进行 Spark 爆炸?

python - 使用scrapy下载图片的正确方法

python - Django 在模型内调用另一个模型的 upload_to

python - 在 Debian 9 上为 Python3 安装 Matplotlib 时出错

Python fiddle 图