python - 有没有办法等待条件为真?
问题描述
当用户单击海龟屏幕时,我尝试分别记录 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)
解决方案
创建列表后是否可以继续运行海龟窗口?
当您尝试使用基于事件的模型时,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
关键是“要遵循的其余代码”将在函数中,而不是顶级代码中。
推荐阅读
- python - Python 最佳实践:最好使用嵌套函数或私有函数语法?
- javascript - 循环json数据并显示在模态表中
- python - 即使我已经按下它,我的键也不起作用 Python Pygame
- r - ggplot核密度图线重叠不正确
- firebase-realtime-database - 如何从 Firebase 数据库密钥中检索/解码时间戳?
- azure-devops - Azure Devops 中的秘密管道参数
- python - 来自 django auth_user 的用户名作为另一个表中的外键
- python - 如何在列先例中的特定列中查找和查找值并将其值放入 Pandas 的新列中
- android - 我试图将一个应用程序部署到使用 kivy 开发的 google playstore。如何从 API 27 升级到 API 30
- javascript - Vanilla JavaScript 切换功能将我的 h2 标签向上移动