2011-03-17 165 views
1

我正在为python中的简单聊天客户端编写代码。我有GUI,一个PHP服务器来存储字符串和其他数据。我想让我的代码能够每隔1秒更新一次聊天(对话文本字段)。 我发表一点的伪代码:执行多线程进程

Initialize Gui 
Setup Users 
UserX write messageX 
messageX sent to server 

在这一点上我需要的东西,检查每个第二,如果用户X(可能是USER1或用户2)有新的消息显示。 如果我把这样的东西:

while True: 
    time.sleep(1) 
    checkAndDisplayNewMessages() 

的GUI没有出现!因为在代码的末尾,我得到了一个mainloop()

要恢复,我希望我的代码给予用户异步发送和接收消息的可能性!使用部分代码发送消息,如果用户输入任何消息,另一部分则在程序运行时不断检查新消息。

+0

你可能想编辑这个问题。仔细查看页面右侧的格式化建议。请让你的代码看起来像代码。 – 2011-03-17 00:29:37

回答

0

您需要分离从应用程序主线程获取新消息的方式。这可以用在Python threads很容易做到,它会是这个样子:

import threading 

def fetch_messages(ui): 
    while not ui.ready(): 
     #this loop syncs this process with the UI. 
     #we don't want to start showing messages 
     #until the UI is not ready 
     time.sleep(1) 

    while True: 
     time.sleep(1) 
     checkAndDisplayNewMessages() 

def mainlogic(): 
    thread_messages = threading.Thread(target=fetch_messages,args=(some_ui,)) 
    thread_messages.start() 
    some_ui.show() # here you can go ahead with your UI stuff 
        # while messages are fetched. This method should 
        # set the UI to ready. 

此实现将并行的过程中运行,以寻求更多的消息,并且还将推出UI。用户界面与进程同步以查找消息非常重要,否则最终会出现有趣的例外情况。这是通过fetch_messages函数中的第一个循环来实现的。