【问题标题】:Display information from socket in a GUI with Tkinter使用 Tkinter 在 GUI 中显示来自套接字的信息
【发布时间】:2014-10-17 07:10:27
【问题描述】:

希望有人可以通过套接字和 GUI 解决这个问题。

我有一个从套接字连接读取信息的客户端,然后我想在 GUI 上的文本框中显示此信息,我使用线程来控制它。在 GUI 中有两个按钮,一个是连接和读取,另一个是停止连接,我使用线程来完成。但我无法管理如何将信息(“recived”)从套接字传递到 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()

【问题讨论】:

    标签: python multithreading sockets user-interface tkinter


    【解决方案1】:

    你没有更新 GUI 上的内容,你只是 print 它。

    尝试像这样在主窗口中添加标签:

    ...
    myLabel = Label(top, text=recived)
    myLabel.pack()
    ...
    

    然后使用config函数更新这个标签的内容。

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

    【讨论】:

    • 我将标签打包在 GUI 内容中。并使用 .config() 尝试更新“measuredistance”函数中的值。有效,非常感谢!!有时一个简单的东西可以解决“大”问题(对我来说很大,我是初学者)。希望这个答案也可以帮助别人。
    猜你喜欢
    • 1970-01-01
    • 2021-05-01
    • 2016-05-30
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 2016-12-22
    • 1970-01-01
    相关资源
    最近更新 更多