I have written this question after reading this question and this other one . I would like to stop the execution of a Python script when a button is pressed. Here the code:
import turtle
from sys import exit
def stop_program():
print("exit function")
exit(0) #raise SystemExit(0) gives the same result
print("after the exit function")
# Create keyboard binding
turtle.listen()
turtle.onkey(stop_program, "q")
# Main function
while True:
# Code: everything you want
If I press the button "q" (even muliple time) the output is:
exit function
exit function
exit function
exit function
exit function
exit function
exit function
...
ie one line every time I press. This means that the exit
works for the function and not for the whole program. Any suggestion?
Dont use the while loop, use turtle.mainloop()
import turtle
from sys import exit
def stop_program():
print("exit function")
exit(0) #raise SystemExit(0) gives the same result
print("after the exit function")
# Create keyboard binding
turtle.listen()
turtle.onkey(stop_program, "q")
turtle.mainloop()
That seems to work fine for me, give it a try.
Try to use: sys.exit(), see if that works. Below code worked for me.
import turtle
import sys
def stop_program():
print("exit function")
sys.exit() #raise SystemExit(0) gives the same result
print("after the exit function")
# Create keyboard binding
turtle.listen()
turtle.onkey(stop_program, "q")
turtle.mainloop()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.