【问题标题】:Executing multiple Python commands at once一次执行多个 Python 命令
【发布时间】:2017-05-01 18:47:21
【问题描述】:

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

【问题讨论】:

  • 我写这篇评论只是为了注意这与在 Python 中并行执行的事情无关(有几种解决方案),而更多地与使用 Python 的 Turtle 模块并行执行动画有关- 这既会限制一个人的选择,也可能会在单独的软件层中强制使用特定的解决方案。

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


【解决方案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)

【讨论】:

  • 由于某种原因,这不适用于海龟图形,但它非常适用于打印、等待和再次打印等其他事情。谢谢。
  • @coDE_RP 你使用的是什么版本的 Python 和 Turtle?它对我有用。
  • 我使用的是 Python 3.5.2 和 Turtle 1.1b
  • 嗯,好的。我使用的是 Python 2.7,所以这可能会有所作为。
【解决方案2】:

您可以使用 turtle 模块附带的计时器事件有效地做到这一点:

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 也不是 异常

【讨论】:

  • 谢谢,这真的很好用!唯一的问题是它实际上并没有同时做这两件事,它只是快速连续地重复它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
  • 2016-11-10
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
相关资源
最近更新 更多