gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:09 24 4
gpt4 key购买 nike

如果我在函数内定义按钮单击处理程序,它就不起作用。在下面的示例中,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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com