【问题标题】:matplotlib, plt.show() in a different method = no on_clickedmatplotlib, plt.show() 在不同的方法 = 没有 on_clicked
【发布时间】:2016-02-09 08:15:21
【问题描述】:

当我将 plt.show() 放在不同的方法中时,无法单击按钮:

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

class ButtonTest:
    def __init__(self):
        ax = plt.axes([0.81, 0.05, 0.1, 0.075])
        bnext = Button(ax, 'Next')
        bnext.on_clicked(self._next)
#         plt.show()

    def show(self):
        print("when i put plt.show() in a different method, it's impossible to click the button")
        plt.show()

    def _next(self, event):
        print("next !")

b = ButtonTest()
b.show()

当鼠标移到按钮上时,按钮甚至没有突出显示。有人知道为什么以及如何解决这个问题吗?

【问题讨论】:

    标签: python matplotlib matplotlib-widget


    【解决方案1】:

    发生的事情是按钮对象在显示图之前被垃圾收集。您需要保留对它的引用。

    例如,如果你改变了

    bnext = Button(...)
    

    self.bnext = Button(...)
    

    一切都应该正常。

    作为一个完整的例子:

    import matplotlib.pyplot as plt
    from matplotlib.widgets import Button
    
    class ButtonTest:
        def __init__(self):
            ax = plt.axes([0.81, 0.05, 0.1, 0.075])
            self.bnext = Button(ax, 'Next')
            self.bnext.on_clicked(self._next)
    
        def show(self):
            plt.show()
    
        def _next(self, event):
            print("next !")
    
    ButtonTest().show()
    

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 2014-03-08
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 1970-01-01
      • 2020-01-16
      • 2022-11-28
      相关资源
      最近更新 更多