I made a simple animation slider for viewing slices of 3D images. I adapted it from this post. One small problem though, after a little sliding around it always freezes up. After some fiddling around I realised that the freeze stops from happening if I add a print statement to my update method. So I figured that it has something to do with threads getting in each others way (I'm no expert, just guessing) so instead of an ugly print statement I tried including a sleep in its place. But t doesn't work! The only thing that stops it from freezing is a print statement. Why might this be?
def animate(img, cmap='viridis', clim=None):
fig, _ = plt.subplots()
index = 0
max_index = len(img)
plot = plt.imshow(img[index])
plt.set_cmap(cmap)
if clim is not None: plt.clim(clim[0], clim[1])
ax = plt.axes([0.25, .03, 0.50, 0.02])
slider = Slider(ax, "Index", 0, (max_index - 1), valinit=index, valfmt='%d')
def update(i):
print("Hello World!") # Delay to stop freeze. Only thing that seems to work, not even sleep works.
i = int(slider.val)
plot.set_data(img[i])
fig.canvas.draw_idle()
slider.on_changed(update)
plt.show()
EDIT: After some further investigation I noticed that if the image is deeper (more slices) even the print statement is not sufficient. Because of this I am starting to believe that it has something to do with that the update method is called too many times in a short time span.
EDIT 2: Calling the function from the python console with animate([np.random.rand(300,300) for _ in range(20)], clim=[0,1]) produces the error on my machine. You need to swipe the slider back and forth rapidly a little while.
EDIT 3: I am using TkAgg version 3.1.2