The problem is not connected with your use of a global variable. I think there are two possibilities:
- If you click in the figure window, but not on the button, waitforbuttonpress will return, but nothing will have been assigned to answer . In this case, answer will be empty and you will see the error.
- I think it is possible that waitforbuttonpress can return before the callback function has run. The following code will then get an empty value for answer and you will see the error. The next time through, answer will have received a value.
Your description and my tests indicate that it's the second of these; more time with the documentation might support the hypothesis.
Either way the solution is this. Replace the call to waitforbuttonpress with
Remove if w == 0 and the corresponding end .
Insert into the callback function as the final statement before end
Then the progress of the main script is tied in properly with the execution of the callback function.
Best Answer