简体   繁体   中英

Close python Turtle module game at keypress

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!!

EDIT

Instead of using sys.exit(), i used window.bye() and that seemed to work just fine. Thanks!

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()

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()

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM