我一次又一次地得到同样的错误。我想知道为什么每当我运行此代码时都会发生这种情况。错误是:
ValueError:无法将字符串转换为float:create
我正在制作一个有乌龟图形的行走者。这个程序运行几秒钟然后弹出一个错误并说python exe停止了。
import turtle
from threading import Thread
# Creating window
wn = turtle.Screen()
wn.setup(700,500)
wn.bgcolor("lightblue")
wn.title("johnny Walker")
# Creating circle
jw_head = turtle.Turtle()
jw_head.color("black")
jw_head.pensize(3)
jw_head.circle(30)
jw_head.hideturtle()
# Creating torso.
tor = turtle.Turtle()
tor.color("black")
tor.pensize(3)
tor.right(90)
tor.forward(150)
tor.hideturtle()
# Left hand.
left_hand = turtle.Turtle()
left_hand.color("black")
left_hand.speed(10)
left_hand.pensize(2)
left_hand.penup()
left_hand.setposition(0,-50)
left_hand.pendown()
left_hand.right(90)
# Right hand.
right_hand = turtle.Turtle()
right_hand.color("black")
right_hand.speed(10)
right_hand.pensize(2)
right_hand.penup()
right_hand.setposition(0,-45)
right_hand.pendown()
right_hand.right(90)
def l_hand():
while True:
angle = 1
while angle < 90:
left_hand.forward(100)
left_hand.hideturtle()
left_hand.clear()
left_hand.penup()
left_hand.setposition(0,-50)
left_hand.pendown()
left_hand.right(1)
angle = angle + 1
left_hand.left(90)
def r_hand():
while True:
angle1 = 1
while angle1 < 90:
right_hand.left(1)
right_hand.forward(100)
right_hand.hideturtle()
right_hand.clear()
right_hand.penup()
right_hand.setposition(0,-45)
right_hand.pendown()
right_hand.left(1)
angle1 = angle1 + 1
right_hand.right(90)
p1 = Thread(target = l_hand)
p2 = Thread(target = r_hand)
p1.start()
p2.start()
p1.join()
p2.join()
答案 0 :(得分:0)
运行代码时出现的错误是:
RuntimeError:主线程不在主循环中
我假设是由于在辅助线程上执行tkinter(它是turtle的基础)代码。您可以将线程与tkinter一起使用,但图形需要穿梭到主线程。
让我们重新开始使用turtle的内置ontimer()
功能而不是线程。我不确定你的人物应该做什么,所以我做了一个简单的动画,他将手臂从直线向下移动到两侧,但速度不同:
from turtle import Turtle, Screen
# Creating window
wn = Screen()
wn.setup(700, 500)
wn.bgcolor('lightblue')
wn.title('johnny Walker')
# Creating circle
jw_head = Turtle(visible=False)
jw_head.speed('fastest')
jw_head.pensize(3)
jw_head.circle(30)
# Creating torso.
tor = Turtle(visible=False)
tor.speed('fastest')
tor.pensize(3)
tor.right(90)
tor.forward(150)
# Left hand.
left_hand = Turtle(visible=False)
left_hand.pensize(2)
left_hand.right(90)
left_hand.forward(50)
left_hand.forward(50) # intentionally duplicated for undo()
# Right hand.
right_hand = Turtle(visible=False)
right_hand.pensize(2)
right_hand.right(90)
right_hand.forward(50)
right_hand.forward(50) # intentionally duplicated for undo()
def l_hand():
left_hand.undo()
left_hand.left(1)
left_hand.forward(50)
wn.update()
if left_hand.heading() < 359:
wn.ontimer(l_hand, 100)
def r_hand():
right_hand.undo()
right_hand.right(1)
right_hand.forward(50)
wn.update()
if right_hand.heading() > 179:
wn.ontimer(r_hand, 50)
wn.tracer(False)
l_hand()
r_hand()
wn.mainloop()
如果你必须使用线程,这里有一个Multithreading With Python Turtle
的例子