[英]RuntimeError: main thread is not in main loop when setting y coordinate on Timer
My son showed my some code he wrote in python ( he's learning through examples and is working on a basic block bouncing app).我儿子向我展示了他在 python 中编写的一些代码(他正在通过示例学习,并且正在开发一个基本的块弹跳应用程序)。
He asked me to add "gravity" to his game so I added a 2 second timer that resets the y coordinate to 0 after pressing 'space'.他让我在他的游戏中添加“重力”,所以我添加了一个 2 秒计时器,在按下“空格”后将 y 坐标重置为 0。
I get "main thread is not in main loop" error message when executing and I read some threads that explained that the timer I am using may not be on the right thread.执行时我收到“主线程不在主循环中”错误消息,并且我阅读了一些线程,这些线程解释了我正在使用的计时器可能不在正确的线程上。 I am not sure how to implement queueing and am wondering if there is an easier solution to this.
我不确定如何实现排队,并且想知道是否有更简单的解决方案。
Thank you!谢谢!
import turtle
from threading import Timer
wn = turtle.Screen()
wn.title("my game")
wn.bgcolor("blue")
wn.setup(width=1000, height=800)
wn.tracer(0)
#person
person = turtle.Turtle()
person.speed(0)
person.shape("square")
person.color("white")
person.shapesize(stretch_wid=1, stretch_len=1)
person.penup()
person.goto(-350, 0)
def personXX():
x = person.xcor()
x += 20
person.setx(x)
def personXY():
x = person.xcor()
x -= 20
person.setx(x)
def personYY():
y = person.ycor()
y += 20
person.sety(y)
r = Timer(2.0, fallToFloor )
r.start()
def fallToFloor():
y = person.ycor()
y -= 20
person.sety(y)
wn.listen()
wn.onkeypress(personXY, "a")
wn.onkeypress(personXX, "d")
wn.onkeypress(personYY, "space")
while 1 == 1 :
wn.update()
Using threading with turtle/tkinter is tricky as the graphics commands can only be invoked from the main thread.使用turtle/tkinter 线程是棘手的,因为图形命令只能从主线程调用。 It can be done, but isn't really needed for this program as we can use turtle's own 'ontimer()` event to achieve the desired result:
它可以完成,但对于这个程序来说并不是真正需要的,因为我们可以使用 turtle 自己的 'ontimer()` 事件来实现所需的结果:
from turtle import Screen, Turtle
def person_forward():
person.forward(20)
def person_backward():
person.backward(20)
def fallToFloor():
person.sety(person.ycor() - 20)
def person_jump():
person.sety(person.ycor() + 20)
screen.ontimer(fallToFloor, 2000) # milliseconds
screen = Screen()
screen.title("My Game")
screen.bgcolor('blue')
screen.setup(width=1000, height=800)
person = Turtle()
person.shape('square')
person.shapesize(stretch_wid=1, stretch_len=1)
person.color('white')
person.speed('fastest')
person.penup()
person.setx(-350)
screen.onkeypress(person_forward, 'd')
screen.onkeypress(person_backward, 'a')
screen.onkeypress(person_jump, 'space')
screen.listen()
screen.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.