如何为 tkinter 和 paho-mqtt-client 定位无限循环?

How to position infinite loops for tkinter and paho-mqtt-client?

这是我的代码

import paho.mqtt.client as mqtt
import json
from 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_connect
client.on_message = on_message

client.connect("test.mosquitto.org", 1883, 60)
client.loop_forever()

不要太担心它现在的作用。我需要了解的是无限循环的概念。

我需要一个无限循环来保持屏幕上的 tkinter window。我还需要一个无限循环来保持 MQTT 客户端连接。

如何在我的代码中放置那些无限循环?如果我将 root.mainloop() 放在 client.loopforever() 之前,我只会在关闭 tkinter window 时访问 MQTT 代码。如果我将 root.mainloop() 放在 client.loopforever() 之后,当我关闭 MQTT 连接时,tkinter window 会出现。

想法是从代理获取消息并在 tkinter 中显示它们 window。请帮助我了解这两个无限循环的位置。

如果事件循环已经存在,则不应使用 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)
<b>client.loop_start()</b>

app = App(root)
root.mainloop()