无法在tkinter的列表框中插入数据

时间:2019-02-06 05:00:59

标签: python-3.x function class tkinter mqtt

我正在使用“ on_message”函数,该函数在receiveText()函数中调用,以接收来自MQTT服务器的传入消息。

正在接收的消息已反映在打印语句中,但无法在列表框中插入。

虽然使用相同的代码行,但它已被插入sendText()函数中。

代码:

class chat_UI:
    def __init__(self, roots, nameLogin, friendLogin):
        roots.title("Chat window")
        self.nameLogin = nameLogin
        self.friendLogin = friendLogin

        self.scrollbar = Scrollbar(roots)  # To see through previous messages.
        self.msg_list = Listbox(roots, height=30, width=100, yscrollcommand=self.scrollbar.set)
        self.msg_list.grid(row=0, column=0, columnspan=1)
        self.scrollbar.grid(sticky = W)
        self.msg_list.grid(sticky = E)
        #self.msg_list.see(END)

        Label(roots, text="Enter Message").grid(row=1,column=0)
        self.entry_field = Entry(roots,width=20)
        self.entry_field.grid(row=1, column=1)

        self.sendB = Button(roots, text='Send', command=self.sendText)
        self.sendB.grid(row=2, column = 1, pady=4, sticky=W) 

        t1 = threading.Thread(target=self.recieveText,args=(friendLogin, nameLogin)) 
        t1.start()
        #t1.join()

    def sendText(self):
        nameLogin = self.nameLogin
        friendLogin = self.friendLogin
        self.message = self.entry_field.get()
        #self.msg_list.insert(END, (self.friendLogin + ": " + recMsg))
        self.msg_list.insert(END, (self.nameLogin + ": " + self.message))
        mqtt_connect(nameLogin).publish(("techieChat/" + nameLogin), str(self.message), qos = 0)

    def on_message(client, userdata, msg):
        print("In on messafe fn")
        global recMsg
        recMsg = str(msg.payload)
        print("message in chat_ui on_mesg fn: " + recMsg)
        self.msg_list.insert(END, recMsg)

    def recieveText(self, friendLogin, nameLogin):
        print("message in receive text message: " + recMsg)
        client = mqtt_connect(friendLogin)
        client.subscribe("techieChat/" + friendLogin)
        client.on_message = chat_UI.on_message

chat_UI类正在从其他类实例化

self.newWindow = Toplevel(self.roots)
chat_UI(self.newWindow, nameLogin, friendLogin)

1 个答案:

答案 0 :(得分:-1)

您是否尝试过使用tk标签?他们可以提供可变信息,如下所示:

        label = tk.Label(textvariable=recMsg)
        label.pack(side="left") #<--- i presume you may want to use grid here