一次执行多个Python命令

时间:2016-12-16 02:41:38

标签: python python-3.x turtle-graphics

我想知道在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)

2 个答案:

答案 0 :(得分: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的turtle模块是建立在Tkinter上的,最近的帖子指出:

  

许多GUI工具包不是线程安全的,而tkinter不是   例外

答案 1 :(得分: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)