【发布时间】:2014-06-27 17:29:15
【问题描述】:
我是 Kivy 的新手,也是 GUI 的新手,但对编程并不陌生。
在使用 Kivy 时,我完全想念船、独木舟和飞机。
在 30 年的编程生涯中,从机器代码、汇编、Fortran、C、C++、Java、Python,我从来没有尝试过使用 Kivy 这样的语言,因为它的文档很薄,因为它太新了。我知道它会变得更好,但我现在正在尝试使用它。
在我的代码中,我正在尝试实现队列,以便我可以获取 Python 套接字数据。在普通的 Python 编程中,我会通过队列进行 IPC - 输入数据,取出数据。
我从 Kivy 了解到,主要来自我在各种论坛上阅读的内容,但不能说我在 kivy.org 的文档中找到了它,我不能执行以下操作:
- Kivy 需要在它自己的线程中。
- Kivy 中的任何东西都不应该睡觉。
- Kivy 中的任何内容都不应该阻塞 IO。
经过大量 Google 搜索后,我发现唯一有用的方法是 informative note here on StackOverFlow 。然而,虽然它几乎解决了我的问题,但答案假设我对 Kivy 的了解比我多;我不知道如何合并答案。
如果有人能花时间整理一个使用该示例的完整简短演示,或者您自己独特的完整答案之一,我将不胜感激!
这是我整理的一些短代码,但它不起作用,因为它阻塞了 get() 调用。
from Queue import Queue
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.clock import Clock
from threading import Thread
class ClockedQueue(BoxLayout):
text1 = StringProperty("Start")
def __init__(self):
super(ClockedQueue,self).__init__()
self.q = Queue()
self.i=0
Clock.schedule_interval(self.get, 2)
def get(self,dt):
print("get entry")
val = self.q.get()
print(self.i + val)
self.i += 1
class ClockedQueueApp(App):
def build(self):
return ClockedQueue()
class SourceQueue(Queue):
def __init__(self):
q = Queue()
for word in ['First','Second']:
q.put(word)
print("SourceQueue finished.")
def main():
th = Thread(target=SourceQueue)
th.start()
ClockedQueueApp().run()
return 0
if __name__ == '__main__':
main()
谢谢!
【问题讨论】:
-
这里的 Kivy 没有问题,您的代码中的其他所有内容都存在问题。
SourceQueue什么都不做,因为它只创建一个临时局部变量。它也从未被代码中的任何其他内容引用。它不需要在线程中,绝对不应该是线程的target。至于get的阻塞,就是用get_nowait抓Queue.Empty一样简单。
标签: kivy