我一直在尝试使用Python3中的海龟模块来制作蛇游戏。当Esc键被按两次时,我希望程序关闭。下面是我到目前为止尝试过的内容,但我似乎无法让它工作(我以前导入了sys模块):
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()
任何帮助都将不胜感激!!
编辑
我没有使用sys.exit(),而是使用了window.bye(),这似乎很好。谢谢!
发布于 2020-02-10 13:38:50
如果我添加了mainloop()
,它从系统中获取键/鼠标事件并发送到海龟窗口,则代码对我有效。您还可以使用window.bye()
退出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()
发布于 2020-02-10 16:38:54
我通常同意@furas (+1),但我会更简单一些,因为在使用这些方法的上下文中,您调用的某些方法实际上是不操作的:
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()
https://stackoverflow.com/questions/60150678
复制相似问题