当来自网络的数据到达时,定期更改窗口颜色

时间:2017-03-13 15:29:32

标签: python tkinter

我有一个监听端口的小程序。我想要实现的是,当来自网络的数据到达时,它应该将窗口颜色改变为该数据。我该如何修改我的代码?

#!/usr/bin/env python
from Tkinter import Tk
import time
import socket

window = Tk()
window.geometry("266x208")
window.title("Claculator")
window.configure(background='#ffffff')
window.mainloop() 


TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 20  # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
print 'Connection address:', addr
while 1:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    print "received data:", data #here comes the data color and it should call window color change
    conn.send(data)  # echo
conn.close()

1 个答案:

答案 0 :(得分:0)

您需要一个无限循环的连接和Tkinter GUI,并且您不能在一个线程中有2个循环。最好的解决方案是为其中一个开始一个新线程。例如:

#!/usr/bin/env python
from Tkinter import Tk
import time
import socket
import threading

TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 20  # Normally 1024, but we want fast response

class Connection(threading.Thread):
    def run(self):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((TCP_IP, TCP_PORT))
        s.listen(1)

        conn, addr = s.accept()
        print 'Connection address:', addr
        while 1:
            data = conn.recv(BUFFER_SIZE)
            if not data: break
            print "received data:", data #here comes the data color and it should call window color change
            self.window.config(background=data)
            self.window.update()
            conn.send(data)  # echo
        conn.close()

window = Tk()
window.geometry("266x208")
window.title("Claculator")
window.configure(background='#ffffff')
thread = Connection()
thread.window = window
thread.start() #start the connection loop
window.mainloop() #start Tkinter's loop

(完全未经测试)。