【发布时间】:2015-09-22 22:51:05
【问题描述】:
我对 python(threading) 和 kivy 有一些问题:
这是一些代码:
import kivy
import threading
import time
from kivy.app import App
from kivy.uix.button import Button
class Thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.counter = 0
def run(self):
while True:
print "Thread is running "+str(self.counter)
app.button.text = self.set_button(self.counter)
app.button.text = str(self.counter)
time.sleep(0.5)
def count(self):
self.counter += 1
app.button.text = str(self.counter)
def set_button(self, value):
app.button.text = str(value)
class MyApp(App):
def __init__ (self, thread_object):
App.__init__(self)
self.thread_object = thread_object
def callback(self,instance):
print('The button <%s> is being pressed' % instance.text)
self.thread_object.count()
def build(self):
self.button = Button(text='Hello World')
self.button.bind(on_press=self.callback)
return self.button
thread = Thread()
thread.start()
app = MyApp(thread)
app.run()
现在 - 此代码通过一个按钮打开一个 kivy 应用程序。任务是:按下按钮一些数据应该出现在线程代码中(它通过“count”方法完成。
问题是相反的方式 - 线程代码应该更改按钮的文本。我尝试了两种方法:
直接写:
app.button.text = str(self.counter)通过“set_button”方法编写:
app.button.text = self.set_button(self.counter)
它们都显示错误“属性错误:'MyApp'对象没有属性'按钮'”。
有没有什么方法可以直接交换数据而无需请求,甚至不用在这里用“thread_object”做指针的东西
def __init__ (self, thread_object):
感谢您的帮助。
【问题讨论】:
-
嘿!目前还不清楚。我有3个问题:你问-> 有没有什么方法可以直接交换数据而不需要请求?,第一个问题是:你要不要使用线程?您问-> 显示错误“属性错误:'MyApp' 对象没有属性'按钮'”第二个问题是:,如果您在 build() 方法上返回小部件,则可以构建应用程序,那你为什么不新建一个继承一个widget的类呢,第三个是:为什么不用kivy语言给按钮一个id呢?
-
嗨,第一个:我想使用线程来计算事物,第二个是通过套接字或串行端口发送这些数据。第二:我是 kivy 的新手,我发布的这段代码就像来自 kivywebpage 的 hello world 示例。第三:我在2年前尝试在另一个项目中使用kv语言,问题是动态构建gui。
标签: python multithreading kivy