最简单的解决方案可能是让您的服务器成为一个非常基本的XMLRPC服务器。有一个Python类可以做到这一点(SimpleXMLRPCServer)。然后,每隔几分钟,让您的客户端连接到该服务器以获取更新的数据。
有关更多信息,请参见http://docs.python.org/library/simplexmlrpcserver.html。
以下是一个真正的快速而肮脏的示例:
服务器代码
from SimpleXMLRPCServer import SimpleXMLRPCServer
score = 0
def get_scores():
global score
score += 1
return score
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(get_scores, "get_scores")
server.serve_forever()
客户端 GUI 代码
import Tkinter as tk
import xmlrpclib
import socket
class SampleApp(tk.Tk):
url = "http://localhost:8000"
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.server = xmlrpclib.ServerProxy(self.url)
self.status = tk.Label(text="", anchor="w")
self.label = tk.Label(text="current score: ?")
self.status.pack(side="bottom", fill="x")
self.label.pack(side="top", fill="both", expand=True)
self.wm_geometry("400x200")
self.after(1000, self.get_latest_scores, 2000)
def update_status(self, message=""):
'''Update the statusbar with the given message'''
self.status.configure(text=message)
self.update_idletasks()
def get_latest_scores(self, interval):
'''Retrieve latest scores and update the UI'''
try:
self.update_status("connecting...")
score = self.server.get_scores()
self.label.configure(text="current score: %s" % score)
self.update_status()
except socket.error, e:
self.update_status("error: %s" % str(e))
self.after(interval, self.get_latest_scores, interval)
if __name__ == "__main__":
app = SampleApp()
app.mainloop()