我想知道在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)
我想知道在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)
爲此,可以使用自帶的龜模塊的定時器事件切實做到:
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的是不是一個 例外
謝謝,這真的很好!唯一的問題是它並不是同時做到這一點,它只是快速連續地重複它們。 –
嘗試使用線程模塊。
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?它爲我工作。 – wg4568
我正在使用Python 3.5.2和Turtle 1.1b –
我是個寫此評論只是要注意,這有少做在Python並行執行的東西(到有幾種解決方案),還有更多與使用Python的Turtle模塊並行執行動畫有關 - 這將限制一個人的選擇,並可能迫使一個特定的解決方案在一個單獨的軟件層。 – jsbueno