Reputation: 79
I've been trying to make the Snake game using the Turtle module in Python3. I want the program to close when the Esc key is pressed twice. Here's what i've tried so far, but I can't seem to get it working (i've previously imported the sys module):
def exitprogram():
sys.exit()
def close():
close = turtle.Turtle()
close.speed(0)
close.color("white")
close.penup()
close.hideturtle()
close.goto(0,0)
close.write("Press ESC again to exit", align="center", font = ("Courier", 24, "normal"))
window.listen()
window.onkeypress(exitprogram, "Escape")
window.listen()
window.onkeypress(close, "Escape")
window.mainloop()
Any help would be greatly appreciated!!
Instead of using sys.exit(), i used window.bye() and that seemed to work just fine. Thanks!
Upvotes: 0
Views: 3180
Reputation: 41905
I generally agree with @furas (+1) but I would go simpler as some methods you invoke are effectively no-ops in the context in which they are used:
from turtle import Screen, Turtle
def close():
window.onkeypress(window.bye, "Escape")
close = Turtle()
close.hideturtle()
# close.color("white")
close.write("Press ESC again to exit", align="center", font=("Courier", 24, "normal"))
window = Screen()
window.onkeypress(close, "Escape")
window.listen()
window.mainloop()
Upvotes: 1
Reputation: 142983
Code works for me if I add mainloop()
which gets key/mouse events from system and sends to turtle's window. You can also use window.bye()
to exit mainloop()
import turtle
def exitprogram():
window.bye()
def close():
close = turtle.Turtle()
close.speed(0)
#close.color("white")
close.penup()
close.hideturtle()
close.goto(0,0)
close.write("Press ESC again to exit", align="center", font = ("Courier", 24, "normal"))
window.listen()
window.onkeypress(exitprogram, "Escape")
window = turtle.Screen()
window.listen()
window.onkeypress(close, "Escape")
window.mainloop()
Upvotes: 3