【问题标题】:Trying to draw a line with Kivy and threading试图用 Kivy 和线程画一条线
【发布时间】:2017-12-09 21:46:26
【问题描述】:

我现在正在制作一个 Kivy 应用程序,在其中的一部分中,我将数据作为浮点数数组获取,我想使用这些数据在 Kivy 中画一条线。 问题是,我希望它不断运行,所以我使用了线程,但 Kivy 不会画线。这是说明问题的代码的精简版本:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line
from threading import Thread


class MyWidget(Widget):
   def Draw(self):
       with self.canvas:
           Line(points=[100, 200, 300, 400])
class MainApp(App):

    def build(self):
        return MyWidget()




Thread(target=MyWidget().Draw).start()
MainApp().run()

我希望这段代码用点 100、200、300、400 画一条线。 但相反,应用程序打开并且什么也不做,我们将不胜感激!

【问题讨论】:

  • 绘图操作必须从主线程执行。尝试为执行绘图的函数运行Clock.schedule_once(your_drawing_function, 0),而不是直接从线程运行它。

标签: python multithreading python-3.x kivy


【解决方案1】:

我稍微修改了你的示例。
尝试在 init 方法中启动线程。因为当您执行MyWidget().Draw 时,您使用的是一个新的MyWidget 对象,而不是您在构建方法中返回的那个对象。所以这条线永远不会被画出来。但是另一个小部件中的线不在屏幕上。
试试这样:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Line, InstructionGroup
from threading import Thread
from random import randint
import time



class MyWidget(Widget):

    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)

        self.ig = InstructionGroup()
        self.line = Line(points=[100, 200, 300, 400])
        self.ig.add(self.line)
        self.canvas.add(self.ig)

        Thread(target=self.draw).start()


    def draw(self):
        while True:
            self.line.points = [randint(0,400) for i in range(4)]
            time.sleep(0.5)



class MainApp(App):

    def build(self):
        return MyWidget()



MainApp().run()

【讨论】:

  • @TalK 你很高兴。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 1970-01-01
  • 2023-04-08
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多