繁体   English   中英

在python turtle程序中混合事件

[英]Mixing events in a python turtle program

我正在尝试编写一个行为类似于使用游戏循环的常规事件驱动程序的python turtle程序。 该程序将尝试混合鼠标,键盘和计时器事件,如下所示。

我的问题是python似乎无法将onkey()事件与ontimer()循环混合。 运行时,程序将对乌龟进行动画处理,并且onclick()事件将起作用。 直到第一次单击鼠标时,按键按键才被注册。 然后,当按下该键退出时,我在shell中得到了很多错误。 bye()方法似乎以一种残酷的方式终止了程序,并且没有优雅地关闭程序。

我认为我的命令顺序正确。

任何建议将不胜感激!

import turtle

playGround = turtle.Screen()
playGround.screensize(800, 600, 'light blue')

bob = turtle.Turtle()
bob.color('red')
bob.pencolor('red')
bob.ht()

def teleport(x,y):
    bob.goto(x,y)

def quitThis():
    playGround.bye()

def moveAround():
   bob.fd(10)
   bob.rt(15)
   playGround.ontimer(moveAround,30)

playGround.onclick(teleport,btn=1)
playGround.onkey(quitThis,'q')

moveAround()

playGround.listen()
playGround.mainloop()

我在您的代码中看到的一个问题是,您需要防止moveAround()teleport()期间发生,否则您会感到困惑。 我发现使用turtle可以帮助在事件处理程序内部禁用事件处理程序,并在退出时重新启用它。

我相信以下内容可以使您的事件变得顺利,并允许它们在适当的时间触发。 我添加了一个状态变量来帮助控制活动:

from turtle import Turtle, Screen

def teleport(x, y):
    global state

    playGround.onclick(None)  # disable handler inside handler

    if state == "running":
        state = "teleporting"
        bob.goto(x, y)
        state = "running"

    if state != "quitting":
        playGround.onclick(teleport)

def quitThis():
    global state

    state == "quitting"

    playGround.onkey(None, 'q')

    playGround.bye()

def moveAround():
    if state == "running":
        bob.fd(10)
        bob.rt(15)

    if state != "quitting":
        playGround.ontimer(moveAround, 30)

playGround = Screen()
playGround.screensize(800, 600, 'light blue')

bob = Turtle(visible=False)
bob.color('red')

playGround.onclick(teleport)
playGround.onkey(quitThis, 'q')
playGround.listen()

state = "running"

playGround.ontimer(moveAround, 100)

playGround.mainloop()

当按下该键退出时,我在shell中得到了大量错误。 bye()方法似乎以一种残酷的方式终止了程序

这是典型的乌龟。 如果确实困扰您,请参阅我对有关Turtle窗口退出错误的问题的答案,以寻求一种可能的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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