How to do it...

First, we create a new Python module in our project. Let's call it Queues.py. We'll place a function into it (no OOP necessary yet).

We pass a self-reference of the class that creates the GUI form and widgets, which enables us to use all of the GUI methods from another Python module.

We do this in the button callback.

This is the magic of OOP. In the middle of a class, we pass ourselves into a function we are calling from within the class, using the self keyword.

The code now looks as follows:

    import Ch06_Code.Queues as bq 

class OOP():
# Button callback
def click_me(self):
# Passing in the current class instance (self)
print(self)
bq.write_to_scrol(self)

The imported module contains the function we are calling:

    def write_to_scrol(inst): 
print('hi from Queue', inst)
inst.create_thread(6)

We have commented out the call to create_thread in the button callback because we are now calling it from our new module:

    # Threaded method does not freeze our GUI 
# self.create_thread()
By passing in a self-reference from the class instance to the function that the class is calling in another module, we now have access to all our GUI elements from other Python modules.

Running the code yields the following result:

Next, we will create the Queue as a member of our class, placing a reference to it in the __init__ method of the class:

    class OOP(): 
def __init__(self):
# Create a Queue
self.gui_queue = Queue()

Now, we can put messages into the queue from our new module by simply using the passed-in class reference to our GUI:

    def write_to_scrol(inst): 
print('hi from Queue', inst)
for idx in range(10):
inst.gui_queue.put('Message from a queue: ' + str(idx))
inst.create_thread(6)

The create_thread method in our GUI code now only reads from the Queue, which got filled in by the business logic residing in our new module, which has separated the logic from our GUI module:

    def use_queues(self): 
# Now using a class member Queue
while True:
print(self.gui_queue.get())

Running our modified code yields the same results. We did not break anything (yet)!

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

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