【问题标题】:Mixing events in a python turtle program在 python 海龟程序中混合事件
【发布时间】:2017-03-29 21:39:30
【问题描述】:

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

我的问题是 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()

【问题讨论】:

    标签: python turtle-graphics


    【解决方案1】:

    我在您的代码中看到的一个问题是您需要在 teleport() 期间防止 moveAround() 发生,否则您会得到令人困惑的视觉效果。我发现 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()
    

    当按下该键退出时,我在 壳。 bye() 方法似乎正在终止程序 野蛮时尚

    这是典型的乌龟。如果它真的困扰您,请参阅我对Turtle window exit errors 问题的回答,了解一种可能的解决方案。

    【讨论】:

      猜你喜欢
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多