Raspberry Pi 3 Cookbook for Python Programmers
上QQ阅读APP看书,第一时间看更新

How it works...

We create the Tkinter window as we did before; however, instead of defining all the items separately, we create a special class for the application buttons.

The class we create acts as a blueprint or specification of what we want the appButtons items to include. Each item will consist of a string value for app_cmd, a function called startApp(), and an __init__() function. The __init__() function is a special function (called a constructor) that is called when we create an appButtons item; it will allow us to create any setup that is required.

In this case, the __init__() function allows us to create a new Tkinter button with the text to be set to an item in app_list and the command to be called in the startApp() function when the button is clicked. The self keyword is used so that the command called will be the one that is part of the item; this means that each button will call a locally defined function that has access to the local data of the item.

We set the value of self.app_cmd to the command from app_list and make it ready for use via the startApp() function. We now create the startApp() function. If we run the application command here directly, the Tkinter window will freeze until the application we have opened is closed again. To avoid this, we can use the Python threading module, which allows us to perform multiple actions at the same time.

The runApplicationThread() class is created using the threading.Thread class as a template—this inherits all the features of the threading.Thread class in a new class. Just like our previous class, we provide an __init__() function for this as well. We first call the __init__() function of the inherited class to ensure it is set up correctly, and then we store the app_cmd value in self.cmd. After the runApplicationThread() function has been created and initialized, the start() function is called. This function is part of threading.Thread, which our class can use. When the start() function is called, it will create a separate application thread (that is, simulate running two things at the same time), allowing Tkinter to continue monitoring button clicks while executing the run() function within the class.

Therefore, we can place the code in the run() function to run the required application (using call(self.cmd)).