0

I've adapted/developed an interactive matplotlib plot that uses a slider to scroll through a series of images. It works as expected when run from the Spyder console, but not when defined within a function in the editor and called from the console. The image is displayed, but the Slider doesn't work. Bizarrely, if an error is thrown before the end of the script interactivity works perfectly.

This is the code I run in the console: (with blank images for reproducibility)

# Generate 10 blank images
frames = np.ones((10,1024,1024))

# Plot the interactive figure starting at frame 0
fig = plt.figure()
ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.2)
im1 = ax.imshow(frames[0])

# Add Slider
frameax = fig.add_axes([0.25, 0.1, 0.65, 0.03])
sframe = Slider(frameax, 'Frame', 0, 10, valinit=0,valstep=1,valfmt='%d')

# Define slide update event
def Update(val):
    im1.set_data(frames[int(val)])
    fig.canvas.draw_idle()

sframe.on_changed(Update)
plt.show()

Yet when I define this same code under a function in a script and call it from the console, the figure displays but I lose all interactivity.

def FrameScroll():

    *** Exact copy of above code***

In Console: FrameScroll()

Adding some junk to the end of the script like 'plt.abc' throws an attribute error but for some reason allows interactivity to work exactly as expected! This behaviour seems very strange and I'm completely stuck, any help is much appreciated!

I'm using Python3.6 in Spyder with Matplotlib version 3.1.3

Tom Halmos
  • 103
  • 5
  • [Solution](https://stackoverflow.com/questions/37025715/matplotlib-slider-not-working-when-called-from-a-function) Found! Not sure why it works but it does – Tom Halmos Jul 01 '20 at 10:41
  • if you put code in function then all variables are local and you can't access them outside function. Python's console was created to make life simpler and it may do some things automatically which in code you have to do manually - ie. it prints all values but in script you have to use `print()`. BTW: matplotlib may use `tkinter` to display it and it can also have some bugs - ie. `tkinter` has bug which removes images created insidie function and assigned to local variable. – furas Jul 02 '20 at 01:16
  • Ah right ok I see, so returning the widgets at the end of the function makes them globally accessible. Thanks! – Tom Halmos Jul 03 '20 at 08:57

0 Answers0