Python Matplotlib slider widget is not updating

前端 未结 1 849
轻奢々
轻奢々 2021-01-22 10:26

i want to use multiple matplotlib canvasses which contain data + a (matplotlib) slider widget. the problem is that the slider widgets are not updating correctly (looks like the

相关标签:
1条回答
  • 2021-01-22 11:00

    I had to make the following changes to get your script to run on my machine.

    import matplotlib
    from Tkinter import *
    matplotlib.use('TkAgg')
    
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    from matplotlib.figure import Figure
    from matplotlib.widgets import Slider
    
    class PlotWidget( Frame ):
    
        def __init__(self, master):
            Frame.__init__(self, master)
            self.figure = Figure(figsize=(5,4), dpi=75)
            self.canvas = FigureCanvasTkAgg(self.figure, self)
    
            self.frame = self.canvas.get_tk_widget()
            self.frame.pack(side=TOP, fill=BOTH, expand=1)
            self.canvas.show()
    
        def add_slider(self):
           a = self.figure.add_axes([0.25, 0.1, 0.65, 0.03], axisbg='lightgoldenrodyellow')
           s = Slider( a, 'range', 0.1, 30.0, valinit=5)
           self.canvas.show()
    
    
    
    root = Tk()
    
    option = 1
    
    if option == 1 or option == 2:
         w =  PlotWidget(root)
         w.pack()
         figure = w.figure
    else:
         f = Frame(root, bd = 6, bg='red')
         figure = matplotlib.figure.Figure(figsize=(5,4), dpi=75)
         canvas = FigureCanvasTkAgg(figure, f)
         canvas.get_tk_widget().pack()
         canvas.show()
         f.pack()
    
    
    if option == 1:
        w.add_slider()
    else:
        a = figure.add_axes([0.25, 0.1, 0.65, 0.03], axisbg='lightgoldenrodyellow')   
        s = Slider( a, 'range', 0.1, 30.0, valinit=5)
    
    root.mainloop()
    

    I believe option 1 doesn't work due to the scope of which the Slider is being created in.

    The example here also creates it in same scope as the figure and show commands.

    If you wanted to move the Slider creation into a function you have that function return the Slider back to the scope outside the function, add as the last line of add_slider return s and then change w.add_slider() to s = w.add_slider()

    or you could store the relevant in the same scope (class member) as canvas and figure e.g self.slider = Slider( a, 'range', 0.1, 30.0, valinit=5).

    Both of these methods make the slider update on mouse event when option = 1.

    0 讨论(0)
提交回复
热议问题