2016-12-16 155 views
0

我想知道在python中同时执行两个或多个命令的最简单方法。例如:一次执行多个Python命令

from turtle import * 

turtle_one=Turtle() 
turtle_two=Turtle() 
turtle_two.left(180) 
#The lines to be executed at the same time are below. 
turtle_one.forward(100) 
turtle_two.forward(100) 
+0

我是个写此评论只是要注意,这有少做在Python并行执行的东西(到有几种解决方案),还有更多与使用Python的Turtle模块并行执行动画有关 - 这将限制一个人的选择,并可能迫使一个特定的解决方案在一个单独的软件层。 – jsbueno

回答

2

为此,可以使用自带的龟模块的定时器事件切实做到:

from turtle import Turtle, Screen 

turtle_one = Turtle(shape="turtle") 
turtle_one.setheading(30) 
turtle_two = Turtle(shape="turtle") 
turtle_two.setheading(210) 

# The lines to be executed at the same time are below. 
def move1(): 
    turtle_one.forward(5) 

    if turtle_one.xcor() < 100: 
     screen.ontimer(move1, 50) 

def move2(): 
    turtle_two.forward(10) 

    if turtle_two.xcor() > -100: 
     screen.ontimer(move2, 100) 

screen = Screen() 

move1() 
move2() 

screen.exitonclick() 

对于线程正如其他人所建议的那样,请阅读Multi threading in Tkinter GUI等帖子中讨论的问题,因为Python的乌龟模块建立在Tkinter上,而且最近的后记:

很多GUI工具包是不是线程安全的,并且Tkinter的是不是一个 例外

+0

谢谢,这真的很好!唯一的问题是它并不是同时做到这一点,它只是快速连续地重复它们。 –

1

尝试使用线程模块。

from turtle import * 
from threading import Thread 

turtle_one=Turtle() 
turtle_two=Turtle() 
turtle_two.left(180) 

Thread(target=turtle_one.forward, args=[100]).start() 
Thread(target=turtle_two.forward, args=[100]).start() 

这将在后台启动turtle_one/two.forward函数,并将100作为参数。

为了更方便,使run_in_background功能...

def run_in_background(func, *args): 
    Thread(target=func, args=args).start() 

run_in_background(turtle_one.forward, 100) 
run_in_background(turtle_two.forward, 100) 
+0

由于某些原因,这对龟图形不起作用,但是对于诸如打印,等待和再次打印等其他事情来说,它非常好。谢谢。 –

+0

@coDE_RP您正在使用什么版本的Python和Turtle?它为我工作。 – wg4568

+0

我正在使用Python 3.5.2和Turtle 1.1b –