一次执行多个 Python 命令
Executing multiple Python commands at once
我想知道在 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)
尝试使用线程模块。
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)
您可以使用 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()
关于线程,正如其他人所建议的,阅读 post 中讨论的问题,例如 ,因为 Python 的 turtle 模块是建立在 Tkinter 上的最近 post 条记录:
a lot of GUI toolkits are not thread-safe, and tkinter is not an
exception
我想知道在 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)
尝试使用线程模块。
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)
您可以使用 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()
关于线程,正如其他人所建议的,阅读 post 中讨论的问题,例如
a lot of GUI toolkits are not thread-safe, and tkinter is not an exception