我有一个虚拟灯泡(Tkinter GUI),我有两个单独的图像,如果灯泡是打开或关闭。我正在尝试弄清楚如何使用MQTT (paho mqtt)来打开或关闭这个虚拟灯泡。我可以发布和订阅主题,我可以使用接收到的消息(“开”或“关”)来确定显示哪个图像,我只是不知道如何在收到新消息时更新它。
这就是我要创建Tkinter GUI的地方
#!/usr/bin/python3
from tkinter import *
from PIL import ImageTk, Image
import os
import sys
root = Tk()
root.geometry("768x1024")
if sys.argv[1]:
if sys.argv[1] == "On":
img = ImageTk.PhotoImage(Image.open("light-on.jpg"))
else:
img = ImageTk.PhotoImage(Image.open("light-off.jpg"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()这就是我订阅主题和检索消息的地方。
#! /usr/bin/python3
import paho.mqtt.client as mqtt #import the client1
import time
import subprocess
import tkinter as tk
import random
def on_message(client, userdata, message):
print("message received " ,str(message.payload.decode("utf-8")))
print("message topic=",message.topic)
print("message qos=",message.qos)
print("message retain flag=",message.retain)
subprocess.call(['./pythongui.py',message.payload.decode()])
broker_address="test.mosquitto.org"
print("creating new instance")
client = mqtt.Client() #create new instance
client.on_message=on_message #attach function to callback
print("connecting to broker")
client.connect(broker_address) #connect to broker
print("Subscribing to topic","house/bulbs/bulb1")
client.subscribe("house/bulbs/bulb1")
client.loop_forever()我知道我可能不应该创建子进程,这可能是完全错误的,但我不知道如何做到这一点。任何建议都将不胜感激。
发布于 2019-08-04 10:11:24
##! /usr/bin/python3
import paho.mqtt.client as mqtt #import the client1
from tkinter import *
from PIL import ImageTk, Image
import os
#Get the window and set the size
window = Tk()
window.geometry('320x200')
#Load both the images
img_on = ImageTk.PhotoImage(Image.open("light-on.jpg"))
img_off = ImageTk.PhotoImage(Image.open('light-off.jpg'))
panel = Label(window, image = img_on)
panel.pack(side = "bottom", fill = "both", expand = "yes")
# This is the event handler method that receives the Mosquito messages
def on_message(client, userdata, message):
msg = str(message.payload.decode("utf-8"))
print("message received " , msg)
#If the received message is light on then set the image the the ‘light on’ image
if msg == "Study/HUE_STATE/on":
panel.configure(image=img_on)
print("****ON")
panel.update()
#If the received message is light off then set the image the the ‘light off’ image
elif msg == "Study/HUE_STATE/off":
panel.configure(image=img_off)
print("****OFF")
panel.update()
broker_address="test.mosquitto.org"
print("creating new instance")
client = mqtt.Client() #create new instance
client.on_message=on_message #attach function to callback
print("connecting to broker")
client.connect(broker_address) #connect to broker
print("Subscribing to topic","home")
client.subscribe("home")
#Start the MQTT Mosquito process loop
client.loop_start()
window.mainloop()https://stackoverflow.com/questions/48798410
复制相似问题