Change variable in onChange

Asked by stephane

I have a loop running while at the same time observing a region on my screen:

def changed(event):
    restart=True

restart=False
region.onChange(100, changed)
region.observe(background=True)

while True:
    if restart:
        #do stuff
    else:
        #do other stuff

region.stopObserver()

This code does not seem to work, ie the value of "restart" is not updated or is not picked up by the while loop.

How could I make this work?

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
RaiMan
Solved:
Last query:
Last reply:
Revision history for this message
Best RaiMan (raimund-hocke) said :
#1

variables being assigned a value are taken as local to the def context and hence not "known" in the main context.

try this:
def changed(event):
    global restart
    restart=True

global makes the given variable name also known in the top-level outside context.

Another comment:
I do not know the timing of your app context:
Be aware: the observation does not stop, but continouosly runs in the background.
So some coordination might be needed between foreground and background.

So you might generally stop the observation in the handler and restart it at the end of the while loop or wherever it makes sense.
So my version:

def changed(event):
    event.stopObserver()
    restart=True

restart=False
region.onChange(100, changed)
region.observe(background=True)

while True:
    if restart:
        #do stuff
    else:
        #do other stuff
    restart = False
    region.observe(background=True)

other valuable options with 1.1.1+ can be found in the docs:
http://sikulix-2014.readthedocs.io/en/latest/region.html#observing-visual-events-in-a-region

Revision history for this message
stephane (su1) said :
#3

Thanks RaiMan, that solved my question.