2011-03-17 164 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函數中的第一個循環來實現的。