我尝试使用导航绘图器将值从MQTT传递到Kivy仪表板。
有人可以提示我如何更改变量吗? 这是我的示例代码。 MQTT正在工作。 我使用的是Python 3.6.6和1.10.1。
mainmenu.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.garden.navigationdrawer import NavigationDrawer
from kivy.properties import StringProperty
import paho.mqtt.client as mqtt
class Drawer(NavigationDrawer):
vartext1 = StringProperty("Button")
vartext2 = StringProperty("Text")
class MainMenuApp(App):
def build(self):
return Drawer()
def on_start(self):
topic = "kivy/#"
def onConnect(client, userdata, flags, rc):
mqttc.subscribe(topic, 0)
def onMessage(client, userdata, msg):
msg.payload = msg.payload.decode("utf-8")
print ("[INFO ] [MQTT ] topic: " + msg.topic +" msg: "+ msg.payload)
if msg.topic == "kivy/button":
vartext1 = msg.payload
if msg.topic == "kivy/text":
vartext2 = msg.payload
mqttc = mqtt.Client(client_id="kivy-client", clean_session=True)
mqttc.on_connect = onConnect
mqttc.on_message = onMessage
mqttc.connect("10.0.0.104", 1883, keepalive=60, bind_address="")
mqttc.loop_start() # start loop to process callbacks! (new thread!)
if __name__ == "__main__":
MainMenuApp().run()
mainmenu.kv
<Drawer>:
# Side panel
BoxLayout:
padding: 30
Button:
text: root.vartext1
# Main panel
BoxLayout:
padding: 30
Label:
text: root.vartext2
答案 0 :(得分:3)
您可以将“ self”参数传递给mqtt.Client构造函数,如下所示:
parameters = {'self': self}
mqttc = mqtt.Client(client_id="kivy-client", clean_session=True, userdata = parameters)
现在在onMessage过程中,您可以访问该参数:
userdata['self'].vartext1 = msg.payload
因此您的mainmenu.py文件应如下所示:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.garden.navigationdrawer import NavigationDrawer
from kivy.properties import StringProperty
import paho.mqtt.client as mqtt
class Drawer(NavigationDrawer):
vartext1 = StringProperty("Button")
vartext2 = StringProperty("Text")
class MainMenuApp(App):
def build(self):
return Drawer()
def on_start(self):
topic = "kivy/#"
def onConnect(client, userdata, flags, rc):
mqttc.subscribe(topic, 0)
def onMessage(client, userdata, msg):
msg.payload = msg.payload.decode("utf-8")
print ("[INFO ] [MQTT ] topic: " + msg.topic +" msg: "+ msg.payload)
if msg.topic == "kivy/button":
userdata['self'].vartext1 = msg.payload
if msg.topic == "kivy/text":
userdata['self'].vartext2 = msg.payload
parameters = {'self': self}
mqttc = mqtt.Client(client_id="kivy-client", clean_session=True, userdata = parameters)
mqttc.on_connect = onConnect
mqttc.on_message = onMessage
mqttc.connect("10.0.0.104", 1883, keepalive=60, bind_address="")
mqttc.loop_start() # start loop to process callbacks! (new thread!)
if __name__ == "__main__":
MainMenuApp().run()
答案 1 :(得分:0)
认为您的问题中缺少.root
的{{1}}。
至少对我来说,当我进行以下更改时,它起作用了。
替换
userdata['self']
到
userdata['self'].vartext2 = msg.payload