这是我的代码import paho.mqtt.client as mqttimport jsonfrom tkinter import *from tkmacosx import *class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print("hi there, everyone!")def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) client.subscribe("$SYS/broker/clients/connected")def on_message(client, userdata, msg): data = json.loads(msg.payload) print(data)root = Tk()client = mqtt.Client()app = App(root)root.mainloop()client.on_connect = on_connectclient.on_message = on_messageclient.connect("test.mosquitto.org", 1883, 60)client.loop_forever()不要太担心它现在做了什么。我需要了解的是无限循环的概念。我需要一个无限循环来将 tkinter 窗口保持在屏幕上。我还需要一个无限循环来保持 MQTT 客户端连接处于活动状态。我如何在我的代码中定位那些无限循环?如果我将 root.mainloop() 放在 client.loopforever() 之前,我只会在关闭 tkinter 窗口时访问 MQTT 代码。如果我将 root.mainloop() 放在 client.loopforever() 之后,则当我关闭 MQTT 连接时会显示 tkinter 窗口。这个想法是从代理获取消息并在 tkinter 窗口中显示它们。请帮助我了解这两个无限循环的位置。
1 回答
波斯汪
TA贡献1811条经验 获得超4个赞
如果事件循环已经存在,则loop_forever()不应使用,但loop_start():
# ...
root = Tk()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("test.mosquitto.org", 1883, 60)
client.loop_start()
app = App(root)
root.mainloop()
添加回答
举报
0/150
提交
取消