问题描述
我正在尝试一些 kivy 代码.我尝试从使用线程库创建的胎面修改 kivy 属性(text_colour
).程序运行正常,但线程没有改变属性.
I'm experimenting with some kivy code. I tried modifing a kivy property(text_colour
) from a tread created with threading lib. Program works fine but the thread does not change the property.
我还尝试在类中创建一个将值作为参数的方法,但也失败了.
I also tried to create a method in class about which gets the value as an argument, which also failed.
输出:
推荐答案
您不能从外部线程修改 kivy 属性或执行任何与 OpenGL 相关的工作.
You cannot modify a kivy property or do any OpenGL related work from an external thread.
解决方案是用 kivy 的 Clock 来安排 callbacks 来调用一个函数来自 kivy 的主线程并为您完成工作.
The solution is to schedule callbacks with kivy's Clock that will call a function from kivy's main thread and do the work for you.
就个人而言,当我使用第二个线程时,我使用队列进行线程间通信,如下所示:
Personally, when I use a second thread, I use a queue for the inter-thread comm as follows:
第二个线程使用 put 将东西放入队列.回调在调用时会使用 trigger.然后kivy的主线程调用的函数调用队列的get函数并设置相应的属性.
The second threads uses put to put things on the queue. And the callback, when called, schedules a kivy callback using a trigger. The function that the kivy's main thread then calls calls the get function of the queue and sets the appropriate property.
如果您需要设置许多属性,这将很有帮助.如果您只需要设置一个属性,我所做的就是从第二个线程中安排一个 callabck,它使用 partial 来使 value 成为函数的一部分.例如:
That is helpful if you need to set many properties. If you just need to set a single property, what I do is from the second thread I schedule a callabck that uses partial to make the value part of the function. E.g:
这篇关于从另一个线程更改 kivy 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!