Tkinter海龟和螺纹

2024-10-04 11:30:03 发布

您现在位置:Python中文网/ 问答频道 /正文

世界!在python中的turtle图形中,可以创建各种各样的turtle对象并用它们的方法操作它们,向前、向后。。。我想尝试线程,所以我写了一个线程类,名为MyTurtleManipulator。在

from threading import Thread
from cTurtle import Turtle 
import random

class MyTurtleManipulator(Thread):
  def __init__(self, turtle):
    Thread.__init__(self)
    self.turtle=turtle
  def run(self):
    actions=[Turtle.forward, Turtle.right, Turtle.left]    
    while True:      
      action=random.choice(actions)      
      action(self.turtle, random.randint(1,25))

turtles=[Turtle() for i in range(5)]
threads=[MyTurtleManipulator(turtle) for turtle in turtles]

for thread in threads:
  print(thread)
  thread.start()

在这个实验中,我希望看到所有海龟“同时”随机地移动,但当我运行程序时,我得到了以下错误:

^{pr2}$

这意味着什么,“主线程不在主循环中”意味着什么。谢谢你的帮助。在


Tags: infromimportselfactionsforinitdef
2条回答

这似乎是python/tkinter的限制as described here,海龟和线程不是朋友

这有其局限性,但仍有可能。答案就在你的错误信息中:

RuntimeError: main thread is not in main loop

将turtle/tkinter操作限制在主线程上。在我的线程的示例中,我的线程用于在我的线程之间进行通信

from threading import Thread, active_count
from turtle import Turtle, Screen
import queue
import random

QUEUE_SIZE = 1  # set higher the more hardware threads you have
ACTIONS = [Turtle.forward, Turtle.right, Turtle.left]
COLORS = ['red', 'black', 'blue', 'green', 'magenta']

class MyTurtleManipulator(Thread):

    def __init__(self, turtle):
        super().__init__()
        self.turtle = turtle

    def run(self):
        for _ in range(100):
            actions.put((self.turtle, random.choice(ACTIONS), random.randint(1, 30)))

def process_queue():
    while not actions.empty():
        turtle, action, argument = actions.get()
        action(turtle, argument)

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

actions = queue.Queue(QUEUE_SIZE)

for color in COLORS:
    turtle = Turtle('turtle')
    turtle.color(color)
    turtle.setheading(random.randint(0, 360))
    MyTurtleManipulator(turtle).start()

screen = Screen()

process_queue()

screen.mainloop()

我将队列大小设置为1,因为我在一台只有两个线程的机器上!我很想知道在一台有更多线程和一个队列的机器上是否一切正常

enter image description here

相关问题 更多 >