[英]matplotlib Button click handler inside a function doesn't work
如果我在函數內部定義了Button Click處理程序,則它將無法正常工作。 在下面的示例中,圖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()
正如文檔所講的只是任何小部件,
為了使按鈕保持響應狀態,您必須保留對其的引用。
因此,您需要從函數返回按鈕以保留對其的引用( 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.