這是我的代碼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()不要太擔(dān)心它現(xiàn)在做了什么。我需要了解的是無(wú)限循環(huán)的概念。我需要一個(gè)無(wú)限循環(huán)來(lái)將 tkinter 窗口保持在屏幕上。我還需要一個(gè)無(wú)限循環(huán)來(lái)保持 MQTT 客戶端連接處于活動(dòng)狀態(tài)。我如何在我的代碼中定位那些無(wú)限循環(huán)?如果我將 root.mainloop() 放在 client.loopforever() 之前,我只會(huì)在關(guān)閉 tkinter 窗口時(shí)訪問(wèn) MQTT 代碼。如果我將 root.mainloop() 放在 client.loopforever() 之后,則當(dāng)我關(guān)閉 MQTT 連接時(shí)會(huì)顯示 tkinter 窗口。這個(gè)想法是從代理獲取消息并在 tkinter 窗口中顯示它們。請(qǐng)幫助我了解這兩個(gè)無(wú)限循環(huán)的位置。
1 回答

波斯汪
TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果事件循環(huán)已經(jīng)存在,則loop_forever()不應(yīng)使用,但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()
添加回答
舉報(bào)
0/150
提交
取消