簡體   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