Home > Enterprise >  How to get out of a while loop using a button in matplotlib
How to get out of a while loop using a button in matplotlib

Time:10-07

I'm trying to figure out how to get out of the while loop with a button, that's all.

This should work in my head, but all it does is that the first time you click it, the while loop starts, and after a few more clicks, the program crashes.

I think the error is in the "bprev.on_clicked(turn_off)" code, which either doesn't work the way I want it to or maybe it's "skipped"

    import matplotlib.pyplot as plt
    import numpy as np
    from matplotlib.widgets import Button
    import time

    onoff = True
    fig, ax = plt.subplots()
    axprev = fig.add_axes([0.7, 0.05, 0.1, 0.075])
    bprev = Button(axprev, 'On/Off')

    def turn_on(val):
        global onoff
        onoff = True
        main()

    def main(): 
        global onoff

        def turn_off(val):
            global onoff       
            onoff = False       
        
        while onoff: #main loop
            bprev.on_clicked(turn_off) 
            print("It works ? Probably not.")
            time.sleep(0.4)        

    bprev.on_clicked(turn_on) 
    plt.show()

CodePudding user response:

you are working on only single thread so you can only interreact with matplot's view after call is over. but this will never happen because its running infinite loop. simple solution is use multithreading.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Button
import time
from threading import Thread

onoff = True
fig, ax = plt.subplots()
axprev = fig.add_axes([0.7, 0.05, 0.1, 0.075])
bprev = Button(axprev, 'On/Off')


def toggle(val):
    global onoff
    onoff = not onoff
    if(onoff == True): Thread(target=main).start()


def main():
    global onoff    
        
    while onoff: #main loop
        print("It works ? Probably not.")
        time.sleep(0.4)        

bprev.on_clicked(toggle) 
plt.show()
  • Related