0

Thanks for the help in advance.

I'm trying to update a matplotlib imshow plot when a slider is moved (Python 3.7.4), but nothing is changing when the update function is called, despite calling canvas.draw which I thought would be all I needed to solve the problem. The code also needs to be embedded in Tkinter. This code will reproduce the problem:

import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

class mainApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.image = np.zeros((10, 10))

        fig = Figure()
        self.mainAx = fig.add_subplot(111)
        self.drawing = self.mainAx.imshow(self.image)

        self.graphCanvas = FigureCanvasTkAgg(fig, master=self)
        self.graphCanvas.draw()
        self.graphCanvas.get_tk_widget().pack(side="top", fill="both", expand=True)

        self.slider = tk.Scale(master=self, command=self.updateGraph, orient="horizontal")
        self.slider.pack(fill="x")

    def updateGraph(self, e):
        self.image = np.zeros((10, 10))
        self.image[self.slider.get()//10, self.slider.get()%10] = 1
        self.drawing.set_data(self.image)
        self.graphCanvas.draw_idle()

main = mainApp()
main.mainloop()

Calling mainAx.imshow(self.image) works but this is far slower and I would like this program to be as fast as possible. I think the issue lies with the draw_idle but I don't know what else I should be doing. It also doesn't work with the regular canvas.draw() function

Thanks, Adam

1 Answers1

0

change your update function to this.

 def updateGraph(self, e):
    self.image = np.zeros((10, 10))
    self.image[self.slider.get()//10, self.slider.get()%10] = 1
    self.drawing = self.mainAx.imshow(self.image)
    self.graphCanvas.draw()

I would also modify your command to wait until a final value is chosen on the slider, unless you want to see it change, you can find how to do this here with an event binding or a delay. TkInter, slider: how to trigger the event only when the iteraction is complete?

John T
  • 234
  • 1
  • 6