Implementing the ListeningThread class in our ChatWindow

To make use of our new ListeningThread, we just need to import it and call its start method:

...
from listeningthread import ListeningThread
...
def __init__(self, master, friend_name, friend_username, friend_avatar, **kwargs):
...
self.listening_thread = None
self.listen()

After importing the class, we add a listening_thread attribute to our __init__ method, then call the listen method to get our ListeningThread running:

def listen(self):
self.listening_thread = ListeningThread(self, self.master.username,
self.friend_username)
self.listening_thread.start()

We set our listening_thread attribute to an instance of the ListeningThread class, passing it our username and friend_username. We then call its start method to begin its loop in the background of our application.

When our ChatWindow is closed, we need to terminate the loop in our thread so that the user will not need to force-close each window. To do that, we need to set the running attribute of our listening_thread to False.

In order to hook an event to happen when the user closes a window, we can utilize the protocol method of a widget, allowing us to execute a function when certain events happen. The string WM_DELETE_WINDOW will correspond to the closing of a window.

Add the following to the __init__ method, just before creating our listening_thread attribute, to hook the necessary event:

self.protocol("WM_DELETE_WINDOW", self.close)

This allows us to run our close method, when the user closes the window:

def close(self):
if hasattr(self, "listening_thread"):
self.listening_thread.running = False
self.after(100, self.close)
else:
self.destroy()

In our close method, we check for the presence of our listening_thread attribute. If we still have it, this means our thread is still running. We update its running attribute to False, so that it will break out of its loop, then schedule this same function to run again after 100 milliseconds.

Since the ListeningThread class will delete its master's listening_thread attribute when it breaks from its loop, when our close function runs again and sees we no longer have this attribute, we will know that the thread has finished and we are safe to use the destroy method to close our ChatWindow.

Our application now has the ability to listen for incoming messages without locking up the GUI. To test this out, run two instances of the friendslist.py file, and one of the server.py. Log into different accounts on each and open up a conversation with the other.

When you type a message into one window, you should see it appear in the second shortly after:

Everybody having the default orange avatar can get a little bit confusing. We should allow the users to upload their own avatar to use, instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset