2014-10-17 247 views
0

希望有人可以用套接字和GUI來解決這個問題。在Tkinter的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() 

回答

0

你沒有更新GUI上的內容,你只是print它。

嘗試收拾一個標籤,你的主窗口是這樣的:

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

然後使用配置功能來更新這個標籤的內容。

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

我在GUI東西里打包了標籤。使用.config()嘗試更新「measuredistance」函數中的值。它的工作原理,非常感謝!有時候一個簡單的東西可以解決「大」的問題(對我來說很重要,我是一個初學者)。希望這個答案也能幫助別人。 – 2014-10-17 09:33:51

相關問題