我有一个虚拟灯泡(Tkinter GUI),如果灯泡打开或关闭,我有两个单独的图像。我试图找出如何使用MQTT(paho mqtt)来打开或关闭这个虚拟灯泡。我可以发布和subscirbe到主题,我可以使用收到的消息(“开”或“关”)来确定要显示的图像,我只是无法弄清楚如何在收到新消息时更新它。
这是我创建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()
我知道我可能不应该创建一个子进程,这可能是完全错误但我无法弄清楚如何做到这一点。任何提示将不胜感激。
答案 0 :(得分:0)
##! /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()