gpt4 book ai didi

python - 使用 Python Turtle 进行多线程处理

转载 作者:行者123 更新时间:2023-11-30 23:32:12 25 4
gpt4 key购买 nike

有没有办法同时使用两只 turtle 在一个窗口中同时画两个圆?我尝试了这段代码,但两只 turtle 在分开的窗口中绘制

from multiprocessing import Process
import turtle

t1=turtle.Turtle()
t2=turtle.Turtle()

def tes1():
t1.speed(0)
i=0
while i < 360:
t1.forward(1)
t1.left(1)
i+=1

def tes2():
t2.speed(0)
i=0
while i < 360:
t2.forward(1)
t2.right(1)
i+=1

if __name__ == '__main__':
p1 = Process(target=tes1)
p1.start()
p2 = Process(target=tes2)
p2.start()
p1.join()
p2.join()

但有人告诉我尝试多线程,但这段代码有一个严重的语义错误!!

import threading
import turtle

t1=turtle.Turtle()
t2=turtle.Turtle()

def tes1():
t1.speed(0)
i=0
while i < 360:
t1.forward(1)
t1.left(1)
i+=1

def tes2():
t2.speed(0)
i=0
while i < 360:
t2.forward(1)
t2.right(1)
i+=1

t = threading.Thread(target=tes1)
t.daemon = True # thread dies when main thread (only non-daemon thread) exits.
t.start()

t3 = threading.Thread(target=tes2)
t3.daemon = True # thread dies when main thread (only non-daemon thread) exits.
t3.start()

多处理或多线程的最佳建议是什么?

最佳答案

... I want multithreading or multiprocessing answer and I'm insisting on it.

如果我们小心地走钢丝,只有主线程发出 turtle 命令, turtle 模块就可以与线程一起使用:

import queue
import threading
import turtle

def tes1():
for _ in range(360):
graphics.put(turtle1.forward)
graphics.put(turtle1.left)

def tes2():
for _ in range(360):
graphics.put(turtle2.forward)
graphics.put(turtle2.right)

def process_queue():
while not graphics.empty():
(graphics.get())(1)

if threading.active_count() > 1:
turtle.ontimer(process_queue, 100)

graphics = queue.Queue(1) # size = number of hardware threads you have - 1

turtle1 = turtle.Turtle('turtle')
turtle1.speed('fastest')
thread1 = threading.Thread(target=tes1)
thread1.daemon = True # thread dies when main thread (only non-daemon thread) exits.
thread1.start()

turtle2 = turtle.Turtle('turtle')
turtle2.speed('fastest')
thread2 = threading.Thread(target=tes2)
thread2.daemon = True # thread dies when main thread (only non-daemon thread) exits.
thread2.start()

process_queue()

turtle.exitonclick()

我们使用队列模块进行线程安全通信。

enter image description here

关于python - 使用 Python Turtle 进行多线程处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19498447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com