首页 > 解决方案 > 有没有办法等待条件为真?

问题描述

当用户单击海龟屏幕时,我尝试分别记录 3 次坐标,然后在完成后继续运行其他命令。单击 3 次没有任何作用,shell 继续打印它正在等待,而再单击一次会导致整个操作无法正常工作,并且我从海龟图形窗口中收到“无响应”消息。

import turtle as t
import time
canvas=t.getcanvas()
xlist=[]
ylist=[]
listcomplete=False

def getPos(x,y):
    xlist.append(canvas.winfo_pointerx())  ##Logs the x and y coords when mouse is clicked
    ylist.append(canvas.winfo_pointery())
    print('appended the lists.')
    if len(xlist)==3:                    
        listcomplete=True

t.onscreenclick(getPos)

def main():
    while listcomplete==False:
        time.sleep(1)
        print('waiting...')     ##Prints periodically just to let me know it's still running


main()

print('list complete.')      ##Prints to alert the list has been finished
print(xlist)
(Insert rest of code to follow)

标签: pythonturtle-graphics

解决方案


创建列表后是否可以继续运行海龟窗口?

当您尝试使用基于事件的模型时,turtle 中的事情会变得很困难。使用模型,事情变得更容易。下面的代码显示了一个空白窗口,当你在三个地方点击它后,它会将你的点连接成一个三角形:

from turtle import Screen, Turtle, mainloop

def getPosition(x, y):
    screen.onscreenclick(None)  # disable the handler inside the handler

    positions.append((x, y))

    if len(positions) == 3:
        screen.ontimer(listComplete)  # sometime after this function completes
    else:
        screen.onscreenclick(getPosition)  # restore the handler

def listComplete():
    for position in positions:
        turtle.goto(position)
        turtle.pendown()

    turtle.goto(positions[0])  # close our triangle

    # (Insert rest of code to follow)

positions = []

turtle = Turtle()
turtle.hideturtle()
turtle.penup()

screen = Screen()
screen.onscreenclick(getPosition)
mainloop()  # invoke as function to make Python 2 friendly as well

关键是“要遵循的其余代码”将在函数中,而不是顶级代码中。


推荐阅读