1

I'm writing a code for a simple chat client in python. I have the GUI, a php server to store strings and other data. I want to make my code capable of updating the chat (conversation Text field) each 1 second. I post a bit of pseudo-code:

Initialize Gui
Setup Users
UserX write messageX
messageX sent to server

At this point I need something that checks each second if userX(that could be user1 or user2) has new messages to display. If I put something like:

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

the GUI doesn't appear! Because at the end of the code I got a mainloop()

To resume, I want my code to give the possibility to the user to send and receive messages asynchronously! With a part of code for sending messages if the user type in any message and the other part to constantly check for new messages while the program runs.

bensiu
  • 24,660
  • 56
  • 77
  • 117
user663468
  • 33
  • 1
  • 3
  • You might want to edit this question. Look carefully at the right side of the page for formatting advice. Please make your code look like code. – S.Lott Mar 17 '11 at 00:29

2 Answers2

0

You did not mention which GUI toolkit you are using; from mainloop() I guess it's Tk.

The answer to this question explains how to set up a recurring event. Multithreading is not required.

Community
  • 1
  • 1
Janne Karila
  • 24,266
  • 6
  • 53
  • 94
0

You need to detach the way you fetch for new messages from the main thread of your applications. That can be easily done with threads in Python, it'd look something like this:

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.

This implementation will run in parallel the process to seek for more messages and also will launch the UI. It is important that the UI is sync with the process to seek for messages otherwise you'd end up with funny exceptions. This is achieved by the first loop in the fetch_messages function.

Manuel Salvadores
  • 16,287
  • 5
  • 37
  • 56