Python 使用Tkinter在GUI中显示来自套接字的信息

Python 使用Tkinter在GUI中显示来自套接字的信息,python,multithreading,sockets,user-interface,tkinter,Python,Multithreading,Sockets,User Interface,Tkinter,希望有人能用socket和GUI解决这个问题 我有一个从套接字连接读取信息的客户端,然后我想在GUI上的文本框中显示此信息,我使用线程来控制它。在GUI中有两个按钮,用于连接和读取,另一个用于停止连接,我使用线程来完成。但是我无法管理如何将从套接字接收到的信息传递到GUI中的标签或文本框。我尝试使用全局变量、文本框、标签等,但仍然无法访问它。以下是代码示例: import socket import Tkinter from Tkinter import Frame, Tk, BOTH, Tex

希望有人能用socket和GUI解决这个问题

我有一个从套接字连接读取信息的客户端,然后我想在GUI上的文本框中显示此信息,我使用线程来控制它。在GUI中有两个按钮,用于连接和读取,另一个用于停止连接,我使用线程来完成。但是我无法管理如何将从套接字接收到的信息传递到GUI中的标签或文本框。我尝试使用全局变量、文本框、标签等,但仍然无法访问它。以下是代码示例:

import socket
import Tkinter
from Tkinter import Frame, Tk, BOTH, Text, Menu, END
import threading
import tkFont

top = Tkinter.Tk()
top.config(bg="gray")
top.geometry("600x600")
top.title("GUI")

s = socket.socket()
rueda = dict()

class Looping(object):
    def __init__(self):
        helv100 = tkFont.Font(family='Helvetica',size=100, weight='bold')
        self.B_start = Tkinter.Button(top, text ="Start",font=helv100, command = self.button_start)
        self.B_start.pack(fill=BOTH, expand=1)
        self.B_stop = Tkinter.Button(top, text ="Stop",font=helv100, command = self.button_stop)
        self.B_stop.pack(fill=BOTH, expand=1)
        self.isRunning = True
    def button_start(self):
        l.isRunning = True
        t = threading.Thread(target = l.measuredistance)
        t.start()        
    def measuredistance(self):        
        global recived
        s = socket.socket()
        s.connect(('172.17.18.21', 6000))  
        while self.isRunning == True:
            recived = s.recv(60)#number of bytes recived
            print recived
        else:
             print "Not connected to the wheel";    
    def button_stop(self):
        l.isRunning = False       
        s.close()
        print "Socket connection breaked"

l=Looping()
top.mainloop()

您没有更新GUI上的内容,您只是将其打印出来

尝试将标签打包到主窗口,如下所示:

...
myLabel = Label(top, text=recived)
myLabel.pack()
...
然后使用config函数更新此标签的内容

...
myLabel.config(text=recived)
...

我将标签打包在GUI中。并使用.config尝试更新MeasureInstance函数中的值。它很有效,非常感谢!!有时候一件简单的事情就能解决大问题。对我来说,我是个初学者。希望这个答案也能帮助别人。