I want to control the execution of some functions, through using some buttons in matplolib
.
I want to pause the execution of a function, which is in my case to break the for loop, for that I used the following in my script:
def pause(mouse_event):
global pauseVal
pauseVal ^= True
def play(mouse_event):
for x in range(int(dataSlider.val),len(listOfMomentsVis)):
if pauseVal == True:
break
else:
image.set_data(listOfMomentsVis[x])
fig.canvas.draw()
dataSlider.set_val(x+1)
time.sleep(timeSleep)
print(x)
What's happening is the that the function would not execute the next time I try to execute it, not during the execution. In other words, the pause
button won't be effective until the next execution.
My question is: how to break the for loop in the middle of execution through an outside button event?
Is that doable or should be some other way? (Could make the for loop listen
to the outside function?!)
PS: I found the following question with the same title, How to break a loop from an outside function, however, the answers were about breaking according to a value in the loop, not a value from outside.
updae
Here is my update version of the script. I took the comments and answers into consideration, made a class, still not getting the desired results.
class animationButtons():
def __init__(self):
self.pauseVal = False
def backward(self, mouse_event):
ref = int(dataSlider.val)
if ref-1<0:
print('error')
else:
image.set_data(listOfMomentsVis[ref-1])
dataSlider.set_val(ref-1)
def forward(self, mouse_event):
ref = int(dataSlider.val)
if ref+1>len(listOfMomentsVis):
ref = int(dataSlider.val)-1
print('error')
else:
image.set_data(listOfMomentsVis[ref])
dataSlider.set_val(ref+1)
print('from forward', dataSlider.val)
def play(self, mouse_event):
for x in range(int(dataSlider.val),len(listOfMomentsVis)):
ref = int(dataSlider.val)
dataSlider.set_val(ref+1)
time.sleep(timeSleep)
print('from play',ref)
if self.pauseVal:
break
def playReverse(self, mouse_event):
for x in range(int(dataSlider.val),0,-1):
ref = int(dataSlider.val)
dataSlider.set_val(ref-1)
time.sleep(timeSleep)
print('from play',ref)
if self.pauseVal:
break
def pause(self, mouse_event):
self.pauseVal ^= True
print(self.pauseVal)
def animate(self, val):
ref = int(dataSlider.val)
image.set_data(listOfMomentsVis[ref])
print('from animate',ref)
fig.canvas.draw()