'Show a Python matplotlib plot and resume at button push

I would like to have an interactive plot with a slider and a button to resume my program when the user is happy with the slider values. The plot.show() in matplotlib stops execution (in command line mode on Mac) but the interactive elements in the plot appear to work. However, the only way to resume is plot.close() and this destroys everything. I cannot update the plot with values returned by the slider. The reason is that what I need to update requires variables that are not in the scope of the callback function. I was hoping to set a global bool variable and change it on a button press, stopping execution with a while loop, checking this boolean, but even with

global is_my_button_pressed 
is_my_button_pressed = False

the value of 'is_my_button_pressed' could not be altered inside the callback. This renders the button and slider useless. I can only print the values of the slider and report a button press, but I cannot do anything useful with it. Somehow axes sliders and figures are accessible within the callbacks, but not other stuff I need to do anything with the figures. Below is a code snippet showing what I want to do

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

#..... stuff before....
slider = make_range_slider( fig = fig, axis = axes[0] )
# Get initial slider limits
lowerfreq = slider.val[0]
highfreq  = slider.val[1]
ok_button_pushed = False
def push_ok(event):
    lowerfreq = slider.val[0]
    highfreq  = slider.val[1]
    ok_button_pushed = True

# Create a tiny axis to draw a button
buttonax = plt.axes([0.81, 0.03, 0.1, 0.07])
# Make the button with the test 'OK'
buttok = Button(buttonax, 'OK')
# Attach the callback
callback_id = buttok.on_clicked( push_ok )
# Set the slider to work
slider = run_range_slider( slider , axes[0] )
# Show the figure and start listening to slider and button
plt.show()
# And now advance, only when the OK button is pushed

So, can the callback be used to break the plt.show() hold without destroying the figure with plt.close(). I tried plt.ion() plt.ioff(), and plt.show(block = True) but that did not help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source