Design a Simple Database Application Using Python Gui Code

Trending blog posts

How to Build a Python GUI Application With wxPython

6808

  • by Priyankur Sarkar
  • 15th Oct, 2019
  • Last updated on 11th Mar, 2021
  • 10 mins read

How to Build a Python GUI Application With wxPython

A Graphical User Interface or GUI is a user interface that includes graphical elements that enable a person to communicate with electronic devices like computers, hand-held devices, and other appliances. It displays information using icons, menus, and graphics. They are handled with the help of a pointing device such as a mouse, trackball or a stylus.

A GUI is basically an application that has windows, buttons and lots of other widgets that allows a user to interact with your application. A web browser is a common example of a GUI that has buttons, tabs, and the main window and where the content is displayed.

It was developed by the Xerox Palo Alto research laboratory in the late 1970s. Today, every OS has its own GUI. Software applications make use of these and develop their own GUIs.

Python contains many GUI toolkits, out which Tkinter, wxPython, and PyQt are the important ones. All these toolkits have the ability to work with Windows, macOS, and Linux with the additional quality of working on mobile phones.

How to get started with wxPython?

wxPython was first released in the year 1998. It is an open-source cross-platform Python GUI toolkit used as a wrapper class around a C++ library called wxWidgets. The main feature of wxPython which distinguishes itself from other toolkits like PyQt and Tkinter is that it uses actual widgets on the native platform where required. This allows the wxPython applications to look native to the operating system in which it is running.

The wxPython toolkit contains a lot of core widgets along with many custom widgets which you can download from the Extra Files section of the wxPython official page.

Here, there is a download of the wxPython demo package which is an application demonstrating the robustness of the widgets included with wxPython. The main advantage of this demo is that you can view it one tab and run it in another and it also allows to edit and re-run the code to observe the changes.

Installing wxPython

You will be using the latest wxPython release, wxPython 4, which is also called the wxPython's Project Phoenix. It is a new implementation of wxPython that aims at improving the speed, maintainability, and extensibility of wxPython. The wxPython 3 and wxPython 2 were built only for Python 2. The maintainer of wxPython rejected a lot of aliases and cleaned up a lot of code to make wxPython more easy and Pythonic.

If you are migrating from an older version of wxPython to wxPython 4, take a look at the following references:

  • Classic version vs project Phoenix
  • Phoenix Migration Guide

The Phoenix version is compatible with both Python 2.7 and Python 3. You can use pip to install wxPython 4:

$ pip install wxpython

You will get a prerequisites section on the Github page of wxPython which will provide information to install wxPython on Linux systems.

You can also look into the Extras Linux section to learn about the Python wheels for both GTK2 and GTK3 versions. To install one of the wheels, use the command below:

$ pip install -U -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-18.04/ wxPython

Remember to modify the command to match with the version of Linux.

Components of GUI

As mentioned earlier, GUI is nothing but an interface that allows user interaction.

Common components of the user interfaces:

  • Main Window.
  • Menu.
  • Toolbar.
  • Buttons.
  • Text Entry.
  • Labels.

These items are generally known as widgets. wxPython supports many other common widgets and many custom widgets that are arranged in a logical manner by a developer to allow user interaction.

Event Loops

A GUI works by waiting for the user to perform an action. This is known as an event. An event occurs when something is typed by the user or when the user uses their mouse to press a button or some widget while the application is in focus.

The GUI toolkit runs an infinite loop called an event loop underneath the covers. The task of the event loop is to act on occurred events on the basis of what the developer has coded the application to do. The application ignores the event when it is not able to catch it.

When you are programming a graphical user interface, make sure to attach the widgets to event handlers in order to make your application do something.

You can also block an event loop to make the GUI unresponsive which will appear to freeze to the user. This is a special consideration for you to keep in mind while working with event loops. Launch a special thread or process whenever a GUI takes longer than a quarter of a second to launch a process.

The frameworks of wxPython contain special thread-safe methods that you can use to communicate back to your application. This informs the thread is finished or given an update.

How to create a Skeleton Application?

An application skeleton is basically used for prototyping. It is a user interface comprising of widgets that do not contain event handlers. You just need to create the GUI and show it to the stakeholders for signing off and avoid spending time on the backend logic.

An example of creating a Hello World application with Python:

              import              wx   application = wx.App() framework = wx.Frame(parent=None, title='Hello World') framework.Show() app.MainLoop()

In the example above, there are two parts of the program – wx.App and wx.Frame. The former one is wxPython's application object which is basically required for running the GUI. It initiates the .MainLoop() which is the event loop you have learned earlier.

The latter part creates a window for user interaction. It informs wxPython that the frame has no parent and its title is Hello World. If you run the code above, this is how it will look like:

How to create a Skeleton Application in Python

The application will look different if you execute it in Mac or Linux.

Note: Mac users may get the following message: This program needs access to the screen. Please run with a Framework build of Python, and only when you are logged in on the main display of your Mac. If you see this message and you are not running in a virtualenv, then you need to run your application with pythonw instead of python. If you are running wxPython from within a virtualenv, then see the wxPython wiki for the solution.

The minimize, maximize and exit will be included in the wx.Frame by default. However, most wxPython code will require you to make the wx.Frame as a subclass and other widgets in order to grab the full power of the toolkit.

Let us rewrite the code using class:

              import              wx              class              MyFramework              (wx.Frame):     def              frame              (self):         super().frame(parent=None, title='Hello World') self.Show()              if              __name__ ==              '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop()

This code can be used as a template for your application.

Widgets in wxPython

The wxPython toolkit allows you to create rich applications from more than one hundred widgets. But it can be very daunting to choose the perfect widget from such a large number, so wxPython has included a wxPython Demo which contains a search filter which will help you to find the right widget from the list.

Now, let us add a button and allow the user to enter some text by adding a text field:

              import              wx              class              MyFramework              (wx.Frame):              def              frame              (self):         super().frame(parent=None, title='Hello World')         panel = wx.Panel(self)   self.text_ctrl = wx.TextCtrl(panel, pos=(5,              5)) my_button = wx.Button(panel, label='Press Me', pos=(5,              55))   self.Show()              if              __name__ ==              '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop()

When you run the code, the application will look like this:

The first widget that is recommended on Windows is wx.Panel. It makes the background color of the frame as the right shade of gray. Tab traversal is disabled without a Panel on Windows.

If the panel is the sole child of the frame, it will be expanded automatically to fill the frame with itself. The next thing you need to do is to add a wx.TextCtrl to the panel. The first argument is always that which parent the widget should go to for almost all widgets. So if you are willing to keep the text control and the button on the top of the panel, it is the parent you need to specify.

You also need to inform wxPython about the position of the widget. You can do it using the pos parameter. The default location is (0,0) which is actually at the upper left corner of the parent. So to change the text control, you can change the position of the frame, you can shift its left corner 5 pixels from the left(x) and 5 pixels from the top(y). Finally, you can add your button to the panel and label it. You can also set the y-coordinate to 55 to prevent the overlapping of widgets.

Absolute Positioning

Absolute positioning is the technique found in most GUI toolkits by which you can provide the exact coordinates for your widget's position.

There might be situations when you need to keep track of all your widgets and relocate the widgets in case of a complex application. This can be a really difficult thing to do. However, most modern-day toolkits provide a solution for this, which we'll study next.

Sizers (Dynamic Sizing)

Sizers are methods to define the control layout in dialogs in wxPython. They have the ability to create dialogs that are not dependent on the platform. They manage the positioning of the widgets and adjust them when the user resizes the application window.

Some of the primary types of sizers that are commonly used are:

  • wx.BoxSizer
  • wx.GridSizer
  • wx.FlexGridSizer

An example code to add wx.BoxSizer to the previous code:

              import              wx              class              MyFramework              (wx.Frame):              def              frame              (self):         super().frame(parent=None, title='Hello World')         panel = wx.Panel(self)         my_sizer = wx.BoxSizer(wx.VERTICAL)         self.text_ctrl = wx.TextCtrl(panel) my_sizer.Add(self.text_ctrl,              0, wx.ALL | wx.EXPAND,              5)         my_button = wx.Button(panel, label='Press Me') my_sizer.Add(my_btn,              0, wx.ALL | wx.CENTER,              5)         panel.SetSizer(my_sizer)         self.Show()              if              __name__ ==              '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop()            

In the example above, an instance of wx.BoxSixer is created and passed to wx.VERTICAL which is actually the orientation that widgets are included in the sizer. The widgets will be added in a vertical manner from top to bottom. You can also set the BoxSizer's orientation to wx.HORIZONTAL. In this case, the widgets are added from left to right.

You can use .Add() to a widget to a sizer which takes maximum five arguments as follows:

  • window ( the widget )- This is the widget that is added to the sizer.
  • proportion - It sets how much space corresponding to other widgets in the sizer will the widget should take. By default, the proportion is zero which leaves the wxPython to its original proportion.
  • flag - It allows you to pass in multiple flags by separating them with a pipe character: |. The text control is added using wx.ALL and wx.EXPAND flags. The wx.ALL flag adds a border on all sides of the widget. On the other hand, wx.EXPAND expands the widgets as much as the sizer can be expanded.
  • border - This parameter informs wxPython about the number of pixels of border needed around the widget.
  • userData - It is a rare argument that is used for resizing in case of complex applications.

However, in this example, the wx.EXPAND flag is replaced with wx.CENTER to display the button in the center on-screen.

When you run the code, your application will look something like this:

Run code of python

Adding an event using wxPython

Though your application looks cool, but it really does nothing. The button you have created does nothing on pressing it. Let us give the button a job:

              import              wx              class              MyFramework              (wx.Frame):              def              frame              (self):         super().frame(parent=None, title='Hello World')         panel = wx.Panel(self)         my_sizer = wx.BoxSizer(wx.VERTICAL)         self.text_ctrl = wx.TextCtrl(panel) my_sizer.Add(self.text_ctrl,              0, wx.ALL | wx.EXPAND,              5)         my_button = wx.Button(panel, label='Press Me') my_button.Bind(wx.EVT_BUTTON, self.on_press) my_sizer.Add(my_btn,              0, wx.ALL | wx.CENTER,              5)         panel.SetSizer(my_sizer)         self.Show()              def              button_press              (self, event):         value = self.text_ctrl.GetValue()              if not              value:             print("You didn't enter anything!")else:             print(f'You typed: "{value}"')              if              __name__ ==              '__main__':     application = wx.App()     framework = MyFramework() application.MainLoop()            

You can attach event bindings to the widgets in wxPython. This allows them to respond to certain types of events.

If you want the button to do something, you can do it using the button's .Bind() method. It takes the events you want to bind to, the handler to call an event, an optional source, and a number of optional ids. In the example above, the button object is binded to wx.EVT_BUTTON and told to call button_press when the event gets fired.

.button_press also accepts a second argument by convention that is called event. The event parameter suggests that the second argument should be an event object.

You can get the text control's contents with the help of GetValue() method within .button_press.

How to create a Working Application?

Consider a situation where you are asked to create an MP3 tag editor. The foremost thing you need to do is to look out for the required packages.

Consider a situation where you are asked to create an MP3 tag editor. The foremost thing you need to do is to look out for the required packages.

If you make a Google search for Python mp3 tag editor, you will find several options as below:

  • mp3 -tagger
  • eyeD3
  • mutagen

Out of these, eyeD3 is a better choice than the other two since it has a pretty nice API that can be used without getting bogged down with MP3's ID3 specification.

You can install eyeD3 using pip from your terminal:

pip install eyed3

If you want to install eyeD3 in macOS, you have to install libmagic using brew. Linux and Windows users can easily install using the command mentioned above.

Designing the User Interface using wxPython

The very first thing you must do before designing an interface is to sketch out how you think the interface should look.

The user interface should perform the following tasks:

  • Open up one or more MP3 files.
  • Display the current MP3 tags.
  • Edit an MP3 tag.

If you want to open a file or a folder, you need to have a menu or a button in your user interface. You can do that with a File menu. You will also need a widget to see the tags for multiple MP3 files. A tabular structure consisting of columns and rows would be perfect for this case since you can have labeled columns for the MP3 tags. wxPython toolkit consists of afew widgets to perform this task:

  • wx.grid.Grid
  • wx.ListCtrl

wx.ListCtrl would be a better option of these two since the Grid widget is overkill and complex in nature. Finally, you can use a button to perform the editing tasks.

Below is an illustration of what the application should look like:

MP3 Tog Editor

Creating the User Interface

You can refer to a lot of approaches when you are creating a user interface. You can follow the Model-View-Controller design pattern that is used for developing user interfaces which divides the program logic into three interconnected elements. You should know how to split up classes and how many classes should be included in a single file and so on.

However, in this case, you need only two classes which are as follows:

  • wx.Panel class
  • wx.Frame class

 Let's start with imports and the panel class:

              import              eyed3              import              glob              importwx              class              Mp3Panel              (wx.Panel):              def              frame              (self, parent):         super().__init__(parent) main_sizer = wx.BoxSizer(wx.VERTICAL) self.row_obj_dict = {}   self.list_ctrl = wx.ListCtrl(             self, size=(-1,              100),               style=wx.LC_REPORT | wx.BORDER_SUNKEN         ) self.list_ctrl.InsertColumn(0,              'Artist', width=140) self.list_ctrl.InsertColumn(1,              'Album', width=140) self.list_ctrl.InsertColumn(2,              'Title', width=200) main_sizer.Add(self.list_ctrl,              0, wx.ALL | wx.EXPAND,              0)         edit_button = wx.Button(self, label='Edit') edit_button.Bind(wx.EVT_BUTTON, self.on_edit) main_sizer.Add(edit_button,              0, wx.ALL | wx.CENTER,              5)         self.SetSizer(main_sizer)              def              on_edit              (self, event):         print('in on_edit')              def              update_mp3_listing              (self, folder_path):         print(folder_path)

In this example above, the eyed3 package, glob package, and the wx package are imported. Then, the user interface is created by making wx.Panel a subclass. A dictionary row_obj_dictis created for storing data about the MP3s.

The next thing you do is create a wx.ListCtrl and set it to report mode, i.e. wx.LC_REPORT. This report flag is the most popular among all but you can also choose your own depending upon the style flag that you pass in. Now you need to call . InsertColumn() to make the ListCtrl have the correct headers and then provide the index of the column, its label and the width of the column pixels.

Finally, you need to add your Edit button, an event handler, and a method. The code for the frame is as follows:

              class              Mp3Frame              (wx.Frame):              def              __init__              (self):         super().__init__(parent=None,                          title='Mp3 Tag Editor') self.panel = Mp3Panel(self) self.Show()              if              __name__ ==                '__main__':     app = wx.App(False)     frame = Mp3Frame() app.MainLoop()

This class function is a better and simpler approach than the previous one because you just need to set the title of the frame and instantiate the panel class, MP3Panel. The user interface will look like this after all the implementations:

The next thing we will do is add a Filemenu to add MP3s to the application and also edit their tags.

Make a Functioning Application

The very first thing you need to do to make your application work is to update the wx.Frame class to include the File menu which will allow you to add MP3 files.

Code to add a menu bar to our application:

              class              Mp3Frame              (wx.Frame):              def              __init__              (self):         wx.Frame.__init__(self, parent=None,                             title='Mp3 Tag Editor') self.panel = Mp3Panel(self) self.create_menu() self.Show()              def                            create_menu              (self): menu_bar = wx.MenuBar() file_menu = wx.Menu() open_folder_menu_item = file_menu.Append( wx.ID_ANY,              'Open Folder',              'Open a folder with MP3s'              ) menu_bar.Append(file_menu,                '&File') self.Bind(             event=wx.EVT_MENU,               handler=self.on_open_folder,             source=open_folder_menu_item,         ) self.SetMenuBar(menu_bar)              def              on_open_folder              (self, event):         title =              "Choose a directory:"              dlg = wx.DirDialog(self, title,                              style=wx.DD_DEFAULT_STYLE)              if              dlg.ShowModal() == wx.ID_OK:             self.panel.update_mp3_listing(dlg.GetPath()) dlg.Destroy()            

In the example code above, .create_menu() is called within the class's constructor and then two instances – wx.MenuBar and wx.Menu are created.

Now, if you're willing to add an item to the menu, you need to call the menu instance's .Append() and pass the following things:

  • A unique identifier
  • Label
  • A help string

After that call the menubar's.Append() to add the menu to the menubar. It will take the menu instance and the label for menu. The label is called as &File so that a keyboard shortcut is created to open theFile menu using just the keyboard.

Now self.Bind() is called to bind the frame to wx.EVT_MENU. This informs wxPython about which handler should be used and which source to bind the handler to. Lastly, call the frame's .SetMenuBar and pass it the menubar instance. Your menu is now added to the frame.

Now let's come back to the menu item's event handler:

              def              on_open_folder              (self, event):     title =              "Choose a directory:"              dlg = wx.DirDialog(self, title, style=wx.DD_DEFAULT_STYLE)              if              dlg.ShowModal() == wx.ID_OK:         self.panel.update_mp3_listing(dlg.GetPath()) dlg.Destroy()

You can use wxPython's wx.DirDialog to choose the directories of the correct MP3 folder. To display the dialog, use .ShowModal(). This will display the dialog modally but will disallow the user to interact with the main application.  You can get to the user's choice of path using .GetPath()whenever the user presses the OK button. This path has to be added to the panel class and this can be done by the panel's .update_mp3_listing().

Finally, you will have to close the dialog and the best method is using .Destroy().  There are methods to close the dialog like .Close() which will just dialog but will not destroy it, so .Destroy()is the most effective option to prevent such situation.

Now let's update the MP3Panel class starting with .update_mp3_listing():

              def              update_mp3_listing              (self, folder_path): self.current_folder_path = folder_path self.list_ctrl.ClearAll()   self.list_ctrl.InsertColumn(0,              'Artist', width=140) self.list_ctrl.InsertColumn(1,              'Album', width=140) self.list_ctrl.InsertColumn(2,              'Title', width=200) self.list_ctrl.InsertColumn(3,              'Year', width=200)       mp3s = glob.glob(folder_path +              '/*.mp3')     mp3_objects = []     index =              0              for              mp3              in              mp3s:         mp3_object = eyed3.load(mp3) self.list_ctrl.InsertItem(index,               mp3_object.tag.artist) self.list_ctrl.SetItem(index,              1,               mp3_object.tag.album) self.list_ctrl.SetItem(index,              2,               mp3_object.tag.title)         mp3_objects.append(mp3_object) self.row_obj_dict[index] = mp3_object         index +=              1            

In the example above, the current directory is set to the specified folder and the list control is cleared. The list controls stay fresh and shows the MP3s you're currently working with. Next, the folder is taken and Python's globmoduleis used to search for the MP3 files. Then, the MP3s are looped over and converted into eyed3 objects. This is done by calling the .load() of eyed3. After that, you can add the artist, album, and the title of the Mp3 to the control list given that the MP3s have the appropriate tags.

.InsertItem() is used to add a new row to a list control for the first time and SetItem()  is used to add rows to the subsequent columns. The last step is to save your MP3 object to your Python dictionary row_obj_dict.

Now to edit an MP3's tags, you need to update the .on_edit() event handler:

              def              on_edit              (self, event):     selection = self.list_ctrl.GetFocusedItem()              if              selection >=              0:         mp3 = self.row_obj_dict[selection]         dlg = EditDialog(mp3)         dlg.ShowModal()         self.update_mp3_listing(self.current_folder_path)         dlg.Destroy()

The user's selection is taken by calling the list control's .GetFocusedItem(). It will return -1 if the user will not select anything in the list control. However, if you want to extract the MP3 obj3ct from the dictionary, the user have to select something. You can then open the MP3 tag editor dialog which will be a custom dialog.

As before, the dialog is shown modally, then the last two lines in.on_edit() will execute what will eventually display the current MP3 tag information.

Summary

Let us sum up what we have learned in this article so far –

  • Installing wxPython and Working with wxPython's widgets
  • Working of events in wxPython
  • Comparing absolute positioning with sizers
  • Creating a skeleton application and a working application

The main feature of the wxPython Graphical User Interface is its robustness and a large collection of widgets that you can use to build cross-platform applications. Since you have now learned how to create a working application, that is an MP3 tag editor, you can try your hand to enhance this application to a more beautiful one with lots of new features or you can perhaps create your own wonderful application. To gain more knowledge about Python tips and tricks, check our Python tutorial and get a good hold over coding in Python by joining the Python certification course.

Suggested Blogs

Subscribe to our newsletter.

Thank You! We have sent an e-mail with a link to confirm your subscription.

Design a Simple Database Application Using Python Gui Code

Source: https://www.knowledgehut.com/blog/programming/python-gui-with-wxpython

0 Response to "Design a Simple Database Application Using Python Gui Code"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel