Course Discount

Search

Python Programming Filter

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 wxPythonYou 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 PhoenixPhoenix Migration GuideThe Phoenix version is compatible with both Python 2.7 and Python 3. You can use pip to install wxPython 4:$ pip install wxpythonYou 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/ wxPythonRemember to modify the command to match with the version of Linux.Components of GUIAs 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 LoopsA 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: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 wxPythonThe 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 PositioningAbsolute 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.BoxSizerwx.GridSizerwx.FlexGridSizerAn 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: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 -taggereyeD3mutagenOut 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 eyed3If 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 wxPythonThe 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.Gridwx.ListCtrlwx.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: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 classwx.Frame class Let’s start with imports and the panel class:import eyed3 import glob import wx   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_dict is 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 File menu to add MP3s to the application and also edit their tags.Make a Functioning ApplicationThe 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 identifierLabelA help stringAfter 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 the File 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 += 1In 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. SummaryLet 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.
Rated 4.5/5 based on 2 customer reviews

How to Build a Python GUI Application With wxPython

6242
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:

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
import wx
 
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_dict is 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 File menu 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 the File 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.

Priyankur

Priyankur Sarkar

Data Science Enthusiast

Priyankur Sarkar loves to play with data and get insightful results out of it, then turn those data insights and results in business growth. He is an electronics engineer with a versatile experience as an individual contributor and leading teams, and has actively worked towards building Machine Learning capabilities for organizations.

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

How to use sys.argv in Python?

The sys module is one of the common and frequently used modules in Python. In this article, we will walk you through how to use the sys module. We will learn about what argv[0] and sys.argv[1] are and how they work. We will then go into how to parse Command Line options and arguments, the various ways to use argv and how to pass command line arguments in Python 3.x In simple terms,Command Line arguments are a way of managing the script or program externally by providing the script name and the input parameters from command line options while executing the script. Command line arguments are not specific just to Python. These can be found in other programming languages like C, C# , C++, PHP, Java, Perl, Ruby and Shell scripting. Understanding sys.argv with examples  sys.argv is a list in Python that contains all the command-line arguments passed to the script. It is essential in Python while working with Command Line arguments. Let us take a closer look with a few examples. With the len(sys.argv) function, you can count the number of arguments. import sys print ("Number of arguments:", len(sys.argv), "arguments") print ("Argument List:", str(sys.argv)) $ python test.py arg1 arg2 arg3 Number of arguments: 4 arguments. Argument List: ['test.py', 'arg1', 'arg2', 'arg3']Module name to be used while using sys.argv To use sys.argv, you will first need to the sys module. What is argv[0]? Remember that sys.argv[0] is the name of the script. Here – Script name is sysargv.py import sys print ("This is the name of the script: ", sys.argv[0]) print ("Number of arguments: ", len(sys.argv)) print ("The arguments are: " , str(sys.argv))Output:This is the name of the script:  sysargv.py                                                                               Number of arguments:  1                                                                                                 The arguments are:  ['sysargv.py']What is "sys. argv [1]"? How does it work? When a python script is executed with arguments, it is captured by Python and stored in a list called sys.argv. So, if the below script is executed: python sample.py Hello Python Then inside sample.py, arguments are stored as: sys.argv[0] == ‘sample.py’ sys.argv[1] == ‘Hello’ sys.argv[2] == ‘Python’Here,sys.argv[0] is always the filename/script executed and sys.argv[1] is the first command line argument passed to the script . Parsing Command Line options and arguments  Python provides a module named as getopt which helps to parse command line options and arguments. Itprovides a function – getopt, whichis used for parsing the argument sequence:sys.argv. Below is the syntax: getopt.getopt(argv, shortopts, longopts=[]) argv: argument list to be passed.shortopts: String of short options as list . Options in the arguments should be followed by a colon (:).longopts: String of long options as list. Options in the arguments should be followed by an equal sign (=). import getopt import sys   first ="" last ="" argv = sys.argv[1:] try:     options, args = getopt.getopt(argv, "f:l:",                                ["first =",                                 "last ="]) except:     print("Error Message ")   for name, value in options:     if name in ['-f', '--first']:         first = value     elif name in ['-l', '--last']:         last = value   print(first + " " + last)Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py -f Knowledge -l Hut Knowledge Hut (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python getopt_ex.py --first Knowledge –last Hut Knowledge HutWhat are command line arguments? Why do we use them? Command line arguments are parameters passed to a program/script at runtime. They provide additional information to the program so that it can execute. It allows us to provide different inputs at the runtime without changing the code. Here is a script named as argparse_ex.py: import argparse parser = argparse.ArgumentParser() parser.add_argument("-n", "--name", required=True) args = parser.parse_args() print(f'Hi {args.name} , Welcome ')Here we need to import argparse package Then we need to instantiate the ArgumentParser object as parser. Then in the next line , we add the only argument, --name . We must specify either shorthand (-n) or longhand versions (--name)  where either flag could be used in the command line as shown above . This is a required argument as mentioned by required=True Output:  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name Nandan  Hi Nandan , Welcome  (venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py -n Nandan  Hi Nandan , Welcome The example above must have the --name or –n option, or else it will fail.(venv) C:\Users\Nandank\PycharmProjects\DSA\venv>python argparse_ex.py --name   usage: argparse_ex.py [-h] --name NAME argparse_ex.py: error: the following arguments are required: --namePassing command line arguments in Python 3.x argv represents an array having the command line arguments of thescript . Remember that here, counting starts fromzero [0], not one (1). To use it, we first need to import sys module (import sys). The first argument, sys.argv[0], is always the name of the script and sys.argv[1] is the first argument passed to the script. Here, we need to slice the list to access all the actual command line arguments. import sys if __name__ == '__main__':     for idx, arg in enumerate(sys.argv):        print("Argument #{} is {}".format(idx, arg))     print ("No. of arguments passed is ", len(sys.argv))Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python argv_count.py Knowledge Hut 21 Argument #0 is argv_count.py Argument #1 is Knowledge Argument #2 is Hut Argument #3 is 21 No. of arguments passed is  4Below script - password_gen.py is used to generate a secret password by taking password length as command line argument.import secrets , sys, os , string ''' This script generates a secret password using possible key combinations''' ''' Length of the password is passed as Command line argument as sys.argv[1]''' char = string.ascii_letters+string.punctuation+string.digits length_pwd = int(sys.argv[1])   result = "" for i in range(length_pwd):     next= secrets.SystemRandom().randrange(len(char))     result = result + char[next] print("Secret Password ==" ,result,"\n")Output:(venv) C:\Users\Nandank\PycharmProjects\DSA\venv\Scripts>python password_gen.py 12 Secret Password == E!MV|,M][i*[Key takeaways Let us summarise what we have learned in this article so far –  The use of the sys module in Python What areargv[0] and sys.argv[1] and how they work What are Command Line arguments and why we use them How to parse Command Line options and arguments Multiple ways to use argv How to pass command line arguments in Python 3.x Hope this mini tutorial has been helpful in explaining the usage of sys.argv and how it works in Python. Be sure to check out the rest of the tutorials on KnowledgeHut’s website! 
Rated 4.0/5 based on 14 customer reviews
5898
How to use sys.argv in Python?

The sys module is one of the common and frequently... Read More

The self variable in Python explained with Python tips

If you have been working on Python, you might have across the self variable. You can find it in method definitions and in initializing variables. However, before coming to the self variable, let us have an idea about classes and instances in Python.  What are Instance methods and Class methods in Python? You might have heard of instances and classes while working on Python. Class variables are defined within a class and they are shared with all the instances (objects) of the class whereas instance variables are owned by the instances of a class. For different instances, the instance variables are different. Likewise, Python also contains class methods and instance methods. The class methods inform about the status of the class. On the other hand, instance methods are to set or get details about instances or objects.   If you want to define an instance method, the foremost parameter of the method should always have to be self. Let us understand this with the help of example code – class myClass:      def instance_method(self):          return “Instance method is called”, self The method “instance_method” is a regular instance method. The method accepts one single parameter – self. The self variable points to an instance of the class myClass when the method is revoked. Though the method takes only one parameter here, it can also accept more than one parameter. The instance methods can easily access different attributes and other methods on the same object with the help of the self variable. The self variable also has the power to modify the state of an object and using the self.__class__  attribute, instance methods can also access the class. Thus, the instance methods are also able to modify the class state. Now, let us see what happens when we call “instance_method”: >>>obj = myClass()  >>>obj.instance_method()  ('Instance method is called', ) This shows that “instance_method” can access the object instance (printed as ) through the self parameter. What happens is that the self parameter is replaced with the instance object obj when the method is called. However, if you pass the instance object manually, you will get the same result as before: >>>myClass.instance_method(obj)  ('Instance method is called', ) Note that self is actually not a defined keyword in Python but a convention.What is Self in Python? Unlike this variable in C++, self is not a keyword rather it is more of a coding convention. It represents the instance or objects of a class and binds the attributes of a class with specific arguments. The use of self variable in Python helps to differentiate between the instance attributes (and methods) and local variables. If you do not want the variables of your class to be shared by all instances of the class, you can declare variables within your class without self. Let us understand this with an example: class Car:      def __init__(self, model):  self.model = model      def Car_info(self):  print("Model : ", self.model) Here, we have declared a class Car with one instance variable self.model = model. The value of the instance variable will be unique to the instance objects of the class that might be declared. However, if you want the variables to be shared by all instances of the class, you need to declare the instance variables without self. Otherwise, it would be ambiguous since all cars will have the same model. Need for Self in Python The self variable is used to represent the instance of the class which is often used in object-oriented programming. It works as a reference to the object. Python uses the self parameter to refer to instance attributes and methods of the class.  Unlike other programming languages, Python does not use the “@” syntax to access the instance attributes. This is the sole reason why you need to use the self variable in Python. The language contains methods that allow the instance to be passed automatically but not received automatically. Explicit definition of self The Zen of Python says “Explicit is better than Implicit”. Programmers of other languages often ask why self is passed as an explicit parameter every time to define a method. There are a few reasons for this. Firstly, since Python uses a method or instance attribute instead of a local variable when we read self.name or self.age, it makes it absolutely clear you are using an instance variable or method even if you have no knowledge about the class definition. Secondly, if you explicitly refer or call a method from a particular class in Python, you do not need to use any special syntax for that.  Finally, the third reason is that the explicit definition of self helps Python understand whether to assign to an instance variable or to a local variable. In simpler terms, local variables and instances exist in two separate namespaces and we need to inform Python which namespace should be used. What is a Python class self constructor? The self variable in Python can also be used to access a variable field within the class definition. Let us understand this with the help of example code: class Student:     def __init__(self, Alex):          self.name = Alex    #name created in constructor      def get_student_name(self):          return self.name In the example above, self refers to the variable age of the class Student. The variable age is local to the method. While the method is running, the variable age exists within the class. If there is a variable within a method, the self variable will not work. If you wish to define global fields, you need to define variables outside the class methods.   Is self a keyword in Python? There is a question that always hovers among Python programmers. Is self actually a keyword in Python? Unlike other programming languages like C++, where self is considered to be a keyword, in Python it is a convention that programmers tend to follow. It is basically a parameter in a method definition. However, you can use any other name in place of self like another or me or anything else for the first parameter of a method. Another reason why it is suggested by most people is that it enhances the readability of your code. Let us see an example to understand it: class myClass:   def show(another):   print(“another is used in place of self”)  If you compare this code with the code for the Python class self constructor, you will notice that here we have used the name another in place of self. Now let us create an object of this class and see the output: object = myClass()   object.show()another is used in place of selfYou can see that the program works even if we use some other name in place of the self variable. It works exactly the same way as the self variable does. Why "self" should be used as the first parameter of instance methods in python  This can be understood by the below example. We have a Rectangle class which defines a method area to calculate the area : class Rectangle ():      def __init__(self,x = 0,y = 0):          self.x = x          self.y = y      def area (self):          """Find area of rectangle"""          return (self.x * self.y)  rec1=Rectangle(6,10)  print ("Area is:", rec1.area()) Output:  Area is: 60    In the above example, __init__() defines three parameters but only 2 arguments are passed (6 and 10). Similarly, area () requires one but no arguments are passed.  Rectangle.area and rec1.area in the above example are different and not exactly the same. >>> type(Rectangle.area )    >>> type(rec1.area)  Here, the first one is a function and the second one is a method. A unique feature of Python is that the object itself is passed as the first argument to the corresponding function. In the above example, the method call:  rec1.area()is equivalent to:  Rectangle.area(rec1). Generally, when the method is called with some arguments, the corresponding class function is called by placing the method's object before the first argument.  Therefore: obj.method(args) becomes Class.method(obj, args). This is the reason the first parameter of a function in a class must be the object itself. Writing this parameter as self is merely a convention and not a keyword so it has no special meaning in Python. We could use other names (like this, that) but it is not preferred as it degrades code readability.Should we pass self to a method? Since we can use any other name instead of using the self variable, then what will happen if we just pass self to a method definition. Let us consider the class myClass we have used earlier.  A method named something is defined within the class with a parameter another and two arguments: class myClass:   def something(another, argument1, argument2):   pass Now, let us declare an instance obj of myClass and call the method something with the help of the instance object: obj = myClass()  obj.something(argument1, argument2) Python performs an internal work on the method call and converts it into something like this: myClass.something(obj, argument1, argument2)  This shows that another variable (used in place of self) refers to the instance object of the class. Note that the pass keyword used in the method something does nothing. It is used as a dummy in situations where you do not want any operation to be performed but there is a syntax requirement of a certain programming element. How can we skip self in Python? Consider a situation where the instance method does not need to have access to the instance variables. In such cases, we can consider skipping the self variable in defining methods. Let us have a clear understanding of the fact with example code: class Vehicle:  def Car():  print(“Rolls Royce 1948”)  obj = Vehicle()  print(“Complete”) If you run the following code, the output will be as follows: Complete We have not declared the self variable here but there is still no error in the program and the output comes out fine. However, what will be the case if we call the Car() method: obj = Vehicle()  obj.Car() When we compile the code after calling the Car() method, it shows an error like this: Traceback (most recent call last):   File "", line 11, in   TypeError: Car() takes 0 positional arguments but 1 was given The output shows an error since the method Car() takes 0 positional arguments but we have given 1 positional argument to it. This is because when the instance obj is created, it is automatically passed as the first argument to the method Car() even if we have not declared the self variable. However, if you try to access the instance method Car() with the help of the class reference, there will be no errors and the program will work fine: class Vehicle:  def Car():  print("Rolls Royce 1948")  obj = Vehicle()  Vehicle.Car()  Rolls Royce 1948 Difference between self and __init__  self : self represents the instance of the class. By using the "self" keyword all the attributes and methods of the python class can be accessed. __init__ : "__init__" is a reserved method in python classes. It is known as a constructor in object oriented concepts. This method is called when an object is created from the class and allows the class to initialize class attributes .. Usage of "self" in class to access the methods and attributes: class Rectangle:     def __init__(self, length, breadth, cost_per_unit =0):         self.length = length         self.breadth = breadth         self.cost_per_unit = cost_per_unit     def perimeter(self):         return 2 * (self.length + self.breadth)     def area(self):         return self.length * self.breadth     def calculate_cost(self):         area = self.area()         return area * self.cost_per_unit  # length = 40 cm, breadth = 30 cm and 1 cm^2 = Rs 100  r = Rectangle(40, 30, 100)  print("Area of Rectangle:",r.area())  print("Cost of rectangular field is : Rs ",r.calculate_cost()) Output:  Area of Rectangle: 1200  Cost of rectangular field is : Rs  120000 We have created an object of Rectangle class. While creating the Rectangle object, we passed 3 arguments – 40,30,100; all these arguments are passed to "__init__"method to initialize the object. Here, the keyword "self” represents the instance of the class. It binds the attributes with the given arguments. Self represents the same object or instance of the class. If you see, inside the method "area” , self.length" is used to get the value of the attribute "length".  attribute "length" is bind to the object (instance of the class) at the time of object creation. "self" represents the object inside the class. "self" works just like "r" in the statement “r = Rectangle(40,30, 100)".  If you see the method definition "def area(self): ” , here "self" is used as a parameter in the method because whenever we call the method,  the object (instance of class) is automatically passed as a first argument along with other arguments of the method. If no other arguments are provided only "self" is passed to the method. That's the reason "self" is used to call the method inside the class("self.area()").  We used object (instance of class) to call the method outside of the class definition("r.area()").  "r" is the instance of the class when the method "r.area()” is called; the instance "r" is passed as first argument in the place of self. Miscellaneous Implementations of self Let us now discuss some of the miscellaneous implementations of the self variable. Similar variables for Class Method and Static Method A class method is a method that is bound to the class. Let us understand a class method with an example – class myClass:  @classmethod  def classmethod(cls):  return “Class Method is called”  obj.classmethod() The same behavior of the self variable is present with the Class methods too but the only difference is that for class methods, the convention is to use cls as the variable name instead of self. The class methods take a cls parameter instead of the self parameter. When the method is called, it points to the class. The class method cannot modify the object state but it can modify the class state of all the class instances. On the other hand, static methods are self-sufficient functions and this type of method takes neither a self nor a cls parameter. Let us see an example of a static method – class myClass:  @staticmethod  def staticmethod():  return “Static Method is called”  obj.staticmethod() Since a static method does not accept any parameter, they cannot modify object state or even class state. They are primarily used to namespace different methods and Python restricts them in the data they can access. Note that both the methods here are marked with @classmethod and @staticmethod decorators to flag it as a class method and static method respectively. The self variable is bound to the current instance The self variable allows us to access the properties of the current instance. Let us understand this with an example – class Person:  def __init__(self, n):  self.name = n  def walk(self):  print(f“{self.name} is walking”)  obj1 = Person(“Alex”)  obj2 = Person(“Charles”)  obj1.walk()  obj2.walk()  Alex is walking Charles is walking Here, we have a class Person with two methods __init__ and walk declared with the self parameter. We have created two different instances of the class – obj1 and obj2. When the first instance is revoked, “Alex” is printed with the method walk() whereas when the second instance is revoked, “Charles” gets printed with the properties of the instance method walk(). Tips about the Python self variable Since we have now reached the end of the article, let me give you some tips about when to use and when not to use the self variable in Python. Use self  – When you are defining an instance method since it is passed automatically as the first parameter when the method is called. While referencing a class or an instance attribute from inside an instance method. When you want to refer to instance variables and methods from other instance methods. Don’t use self – When you want to call an instance method normally. While referencing a class attribute inside the class definition but outside an instance method. When you are inside a static method.  Conclusion Let us go through the points we have covered in this article - Instances and Classes in Python. Self variable and its importance. The explicitness of the self variable. Python class self constructor. Passing self as a method. Skipping self in Python. Variables used for Class methods and Static methods. Bounding of self to the current instance. When to use and when not to use self in Python. You have gathered enough knowledge about the self variable in Python and its internal working in Python. However, if you wish to know more about Python self, you can always head on to the official documentation of Python. 
Rated 4.0/5 based on 10 customer reviews
12356
The self variable in Python explained with Python ...

If you have been working on Python, you might have... Read More

How to Work with Excel Spreadsheets using Python

Excel is considered as one of the most popular and widely used spreadsheet applications developed by Microsoft. You can organize, analyze and store your data into tabular sheets with the help of Excel. From analysts and sales managers, to CEOs, professionals from every field use Excel for creating quick statistics and for data crunching.Spreadsheets are commonly used in the present world because of their intuitive nature and the ability to handle large datasets. Most importantly, they can work without any prior technical background.Finding different ways to work with Excel using code is essential since working with data and in Python has some serious advantages in comparison with Excel’s UI. Developers of Python have implemented ways to read, write and manipulate Excel documents.You can check the quality of your spreadsheet application by going over the checklist below:Is the spreadsheet able to represent static data?Is the spreadsheet able to mix data, calculations, and reports?Is the data in your spreadsheet complete and consistent in nature?Does the spreadsheet have an organized worksheet structure?This checklist will help you in verifying the qualitative nature of the spreadsheet application you’re going to work on.Practical Applications  In this article, we would be using openpyxl to work on data. With the help of this module, you can extract data from a database into an Excel spreadsheet or you can also convert an Excel spreadsheet into a programmatic format. There can be a lot of possible situations where you might feel the need to use a package like openpyxl. Let us discuss a few of them to get a comprehensive overview of it.Importing New Products Into a Database Consider yourself working in an online store company. When they want to add new products to the online store, they make an Excel spreadsheet with a few hundred rows along with the name of the product, description, price and a few more basic information and then they give it to you. Now, if you want to import this particular data, you need to iterate over each row of the spreadsheet and then add each of the products into the database of the online store.[Text Wrapping Break] Exporting Database Data Into a SpreadsheetConsider you have a Database table. In this particular table, you have collected information of all your users which includes their name, contact number, email address, and so forth. Now, the Marketing Team is willing to collectively contact all the users and promote a new product of the company. However, neither do they have access to the Database nor they have any idea about using SQL to extract the information. In this situation, openpyxl comes to play. You can use it effectively to iterate over each User record and transform the required information into an Excel spreadsheet.    Appending Information to an Existing SpreadsheetConsider the same online store example we discussed above. You have an Excel spreadsheet with a list of users and your job is to append to each row the total amount they have spent in your store.In order to perform this, you have to read the spreadsheet first and then iterate through each row and fetch the total amount spent from the Database. Finally, you need to write it back to the spreadsheet.Starting openpyxlYou can install the openpyxl package using pip. Open your terminal and write the following command: $ pip install openpyxlAfter you have installed the spreadsheet, you can make up your own simple spreadsheet: from openpyxl import Workbook workbook = Workbook() spreadsheet = workbook.active spreadsheet["A1"] = "Hello" spreadsheet["B1"] = "World!" workbook.save(filename="HelloWorld.xlsx")How to Read Excel Spreadsheets with openpyxl Let us start with the most important thing that you can do with a spreadsheet,i.e. read it. We will be using a Watch Sample Dataset which contains a list of 100 watches with information like product name, product ID, review and so forth.  A Simple Way to Read an Excel Spreadsheet Let us start with opening our sample spreadsheet:>>> from openpyxl import load_workbook >>> workbook = load_workbook(filename="sample.xlsx") >>> workbook.sheetnames ['Sheet 1'] >>> spreadsheet = workbook.active >>> spreadsheet >>> spreadsheet.titleIn the example code above, we open the spreadsheet using load_workbook and then we check all the sheets that are available to work with using workbook.sheetnames. Then Sheet 1 is automatically selected using workbook.active since it is the first sheet available. This is the most common way of opening a spreadsheet.  Now, let us see the code to retrieve data from the spreadsheet: >>> spreadsheet["A1"] >>> spreadsheet["A1"].value 'marketplace' >>> spreadsheet["F10"].value "G-Shock Men's Grey Sport Watch"You can retrieve the actual value and the cell value  both. To get the actual value, use .value and to get the cell, you can use .cell():>>> spreadsheet.cell(row=10, column=6) >>> spreadsheet.cell(row=10, column=6).value "G-Shock Men's Grey Sport Watch"Importing Data from a Spreadsheet In this section, we will discuss how to iterate through the data, and about conversion into a more useful format using Python.Let us first start with iterating through the data. There are a number of iterating methods that depend solely on the user.You can slice the data with a combination of rows and columns:>>> spreadsheet["A1:C2"] ((, , ),  (, , )) You can also iterate through the dataset by ranging between rows and columns: >>> # Get all cells from column A  >>> spreadsheet["A"] (,  ,   ...   ,   ) >>> # Get all cells for a range of columns >>> spreadsheet["A:B"]  ((,    ,    ...    ,    ),   (,    ,    ...    ,    ))  >>> # Get all cells from row 5 >>> spreadsheet[5] (,  ,  ...   ,  ) >>> # Get all cells for a range of rows >>> spreadsheet[5:6] ((,   ,    ...    ,    ),   (,    ,    ...    ,    )) Python offers arguments by which you can set limits to the iteration with the help of Python generators like .iter_rows() and .iter_cols(): >>> for row in spreadsheet.iter_rows(min_row=1, ... max_row=2, ... min_col=1, ... max_col=3): ... print(row) (, , ) (, , ) >>> for column in spreadsheet.iter_cols(min_row=1,  ... max_row=2, ... min_col=1, ... max_col=3): ... print(column) (, ) (, )  (, ) You can also add Boolean values_only in the above example and set it to True to get the values of cell: >>> for value in spreadsheet.iter_rows(min_row=1,  ... max_row=2,  ... min_col=1,  ... max_col=3,  ... values_only=True): ... print(value) ('marketplace', 'customer_id', 'review_id') ('US', 3653882, 'R3O9SGZBVQBV76')Since we are now done with iterating the data, let us now manipulate data using Python’s primitive data structures. Consider a situation where you want to extract information of a product from the sample spreadsheet and then store it into the dictionary. The key to the dictionary would be the product ID.   Convert Data into Python classesTo convert data into Python data classes, let us first decide what we want to store and how to store it.  The two essential elements that can be extracted from the data are as follows:                                                     1. Products                                             2. Review                                                          • ID                                                         • ID                                                          • Title                                                     • Customers ID                                                          • Parent                                                 • Headline                                                          • Category                                            • Body                                                                                                                         • DateLet us implement the two elements: import datetime from dataclasses import dataclass @dataclass class Product: id: str parent: str title: str category: str @dataclass class Review: id: str customer_id: str stars: int headline: str body: str  date: datetime.datetime The next step is to create a mapping between columns and the required fields: >>> for value in spreadsheet.iter_rows(min_row=1, ... max_row=1, ... values_only=True): ... print(value) ('marketplace', 'customer_id', 'review_id', 'product_id', ...) >>> # Or an alternative >>> for cell in sheet[1]: ... print(cell.value) marketplace Customer_ID Review_ID Product_ID Product_Parent ...Finally, let us convert the data into new structures which will parse the data in spreadsheet into a list of products and review objects: from datetime import datetime  from openpyxl import load_workbook  from classes import Product,Review  from mapping import PRODUCT_ID,PRODUCT_PARENT,PRODUCT_TITLE, \ PRODUCT_CATEGORY,REVIEW_DATE,REVIEW_ID,REVIEW_CUSTOMER, \ REVIEW_STARS,REVIEW_HEADLINE,REVIEW_BODY # Using the read_only method since you're not gonna be editing the spreadsheet workbook = load_workbook(filename="watch_sample.xlsx",read_only=True)  spreadsheet = workbook.active products = [] reviews = [] # Using the values_only because you just want to return the cell value for row in spreadsheet .iter_rows(min_row=2, values_only=True):  product = Product(id=row[PRODUCT_ID],  parent=row[PRODUCT_PARENT],  title=row[PRODUCT_TITLE],  category=row[PRODUCT_CATEGORY])  products.append(product) # You need to parse the date from the spreadsheet into a datetime format spread_date = row[REVIEW_DATE]  parsed_date = datetime.strptime(spread_date,"%Y-%m-%d") review = Review(id=row[REVIEW_ID], Customer_ID=row[REVIEW_CUSTOMER], stars=row[REVIEW_STARS], headline=row[REVIEW_HEADLINE], body=row[REVIEW_BODY], date=parsed_date) reviews.append(review) print(products[0]) print(reviews[0])After you execute the code, you will get an output that looks like this:Product(id='A90FALZ1ZC',parent=937111370,...) Review(id='D3O9OGZVVQBV76',customer_id=3903882,...)Appending Data To understanding how to append data, let us hover back to the first sample spreadsheet. We will open the document and append some data to it: from openpyxl import load_workbook # Start by opening the spreadsheet and selecting the main sheet workbook = load_workbook(filename="hello_world.xlsx") spreadsheet = workbook.active # Write what you want into a specific cell spreadsheet["C1"]="Manipulating_Data ;)" # Save the spreadsheet workbook.save(filename="hello_world_append.xlsx"If you open your Excel file, you will notice the additional Manipulating_Data being added to an adjacent cell. Writing Excel Spreadsheets With openpyxl A spreadsheet is a file that helps to store data in specific rows and columns. We can calculate and store numerical data and also perform computation using formulas. So, let’s begin with some simple Spreadsheets and understand what each line means. Creating our first simple Spreadsheet 1 from openpyxl import Workbook  2    3 filename = "first_program.xlsx"  4    5 workbook = Workbook()  6 spreadsheet = workbook.active  7    8 sheet["A1"] = "first"  9 sheet["B1"] = "program!" 10   11 workbook.save(filename=filename)Line 5: In order to make a Spreadsheet, at first,  we have to create an Empty workbook to perform further operations. Lines 8 and 9 : We can add data to a specific cell as per our requirement. In this example, we can see that two values “first” and “program” have been added to specific cells in the sheet. Line 11: The line shows how to save data after all the operations we have done. Basic Spreadsheet Operations Before going to the difficult coding part, at first we have to build our building blocks like how to add and update values, how to manage rows and columns, adding filters, styles or formulas in a Spreadsheet. We have already explained the following code by which we can add values to a Spreadsheet: >>> spreadsheet["A1"] = "the_value_we_want_to_add"There is another way that we can add values to Spreadsheet: >>> cell = sheet["A1"] >>> cell >>> cell.value 'hello' >>> cell.value = "hey" >>> cell.value 'hey'Line 1: In the first line at first we have declared the cell and updated its value. Line 5: We have printed the value of the cell as “first”  because  in the first program we have already assigned sheet["A1"]with “first” Line 8 : We have updated the value of the cell as "second"by simply assigning it to cell.value. Lines 9 : In this line, we have just printed the updated value of cell. Finally, you have to save all the operations you have performed into the spreadsheet once you call workbook.save().If  the cell didn’t exist while adding a value ,then openpyxl creates a cell:>>> # Before, our spreadsheet has only 1 row >>> print_rows() ('first', 'program!') >>> # Try adding a value to row 10 >>> spreadsheet["B10"] = "test" >>> print_rows() ('first', 'program!') (None, None)  (None, None)  (None, None)  (None, None)  (None, None)  (None, None)  (None, None)  (None, None)  (None, 'test') Managing Rows and Columns in Spreadsheet Insertion or deletion of rows (adding or removing elements of rows /columns) is one of the most basic operations in Spreadsheet. In openpyxl.We can perform these operations by simply calling these methods and passing its arguments. .insert_rows().delete_rows().insert_cols().delete_cols()We can pass 2 types of arguments to the methods :  idx amount Idx stands for index position and amount refers to the number of values we can store in the Spreadsheet. Using our basic knowledge based on the first  simple program, let’s see how we can use these methods inside the program: >>> print_rows() ('first', 'program!') >>> # Insert a column at the first position before column 1 ("A") >>> spreadsheet.insert_cols(idx=1) >>> print_rows() (None, 'first', 'program!') >>> # Insert 5 columns in  between column 2 ("B") and 3 ("C") >>> spreadsheet.insert_cols(idx=3,amount=5) >>> print_rows() (None, 'first', None, None, None, None, None, 'program!') >>> # Delete the created columns >>> spreadsheet.delete_cols(idx=3,amount=5) >>> v.delete_cols(idx=1) >>> print_rows() ('first', 'program!') >>> # Insert a new row in the beginning >>> spreadsheet.insert_rows(idx=1) >>> print_rows() (None, None) ('first', 'program!') >>> # Insert 3 new rows in the beginning  >>> spreadsheet.insert_rows(idx=1,amount=3) >>> print_rows() (None, None) (None, None)  (None, None)  (None, None)  ('first', 'program!') >>> # Delete the first 4 rows  >>> spreadsheet.delete_rows(idx=1,amount=4)  >>> print_rows()  ('first', 'program!') Managing SheetsWe have seen the following recurring piece of code in our previous examples .This is one of the ways of selecting the default sheet from the Spreadsheet: spreadsheet = workbook.activeHowever, if you want to open a spreadsheet with multiple sheets, you can write the following command: >>> # Let's say you have two sheets: "Products" and "Company Sales" >>> workbook.sheetnames ['Products', 'Company Sales'] >>> # You can select a sheet using its title >>> Products_Sheet = workbook["Products"] >>> Sales_sheet = workbook["Company Sales"]If we want to change the title of the Sheet, execute the following code: >>> workbook.sheetnames ['Products', 'Company Sales'] >>> Products_Sheet = workbook["Products"] >>> Products_Sheet.title = "New Products" >>> workbook.sheetnames ['New Products', 'Company Sales']We can CREATE / DELETE Sheets also with the help of two methods - .create_sheet() and  .remove(): >>> #To print the available sheet names >>> workbook.sheetnames  ['Products', 'Company Sales'] >>> #To create a new Sheet named "Operations" >>> Operations_Sheet = workbook.create_sheet("Operations") >>> #To print the updated available sheet names >>> workbook.sheetnames ['Products', 'Company Sales', 'Operations'] >>> # To define the position Where we want to create the Sheet(here “HR” sheet is created at the first position .Here index 0 represents the first position) >>> HR_Sheet = workbook.create_sheet("HR",0) >>> #To again  print the updated available sheet names >>> workbook.sheetnames ['HR', 'Products', 'Company Sales', 'Operations'] >>> # To remove them,we just have to send the sheet names as an argument which we want to delete to the method  .remove()  >>> workbook.remove(Operations_Sheet) >>> workbook.sheetnames ['HR', 'Products', 'Company Sales'] >>> #To delete hr_sheet >>> workbook.remove(hr_sheet) >>> workbook.sheetnames ['Products', 'Company Sales']Adding Filters to the Spreadsheet We can use openpyxl to add filters in our Spreadsheet but when we open our Spreadsheet, the data won’t be rearranged according to these sorts and filters. When you’re programmatically creating a spreadsheet and it is going to be sent and used by someone else, it is a good practice to add different filters and allow people to use it afterward. In the code below there is a simple example which shows how to add a simple filter to your spreadsheet: >>> # Check the used spreadsheet space using the attribute "dimensions" >>> spreadsheet.dimensions 'A1:O100' >>> spreadsheet.auto_filter.ref="A1:O100" >>> workbook.save(filename="watch_sample_with_filters.xlsx")Adding Formulas to the Spreadsheet Formulas are one of the most commonly used and powerful features of spreadsheets. By using formulas, you can solve various mathematical equations with the additional support of openpyxl which makes those calculations as simple as editing a specific cell’s value.The list of formulas supported by openpyxl are:>>> from openpyxl.utils import FORMULAE >>> FORMULAE frozenset({'ABS',            'AMORLINC',            'ACCRINT',             'ACOS',             'ACCRINTM',             'ACOSH',              ...,                   'AND',            'YEARFRAC',             'YIELDDISC',             'AMORDEGRC',             'YIELDMAT',             'YIELD',             'ZTEST'}) Let’s add some formulas to our spreadsheet. Let’s check the average star rating of  the 99 reviews within the spreadsheet: >>> # Star rating is in column "H"  >>> spreadsheet["P2"] = "=AVERAGE(H2:H100)" >>> workbook.save(filename = "first_example.xlsx")Now, if we open your spreadsheet and go to cell P2, you can see the value to be 4.18181818181818.  Similarly, we can use this methodology to include any formulas for our requirements in our spreadsheet. For example, if we want to count the number of helpful reviews: >>> # The helpful votes  counted in column "I"  >>> spreadsheet["P3"] = '=COUNTIF(I2:I100, ">0")' >>> workbook.save(filename = "first_example.xlsx") Adding Styles to the SpreadsheetIt is not so important and usually, we don’t use this in everyday code but for the sake of completeness, we will also understand this with the following example.Using openpyxl, we get multiple styling options such as including fonts, colors,  borders,and so on.Let’s have a look at an example:>>> # Import necessary style classes >>> from openpyxl.styles import Font,Color,Alignment,Border,Side,colors >>> # Create a few styles >>> Bold_Font = Font(bold=True) >>> Big_Red_Text = Font(color=colors.RED,size=20)  >>> Center_Aligned_Text = Alignment(horizontal="center")  >>> Double_Border_Side = Side(border_style="double")  >>> Square_Border = Border(top=double_border_side,  ... right=double_border_side,  ... bottom=double_border_side,  ... left=double_border_side)  >>> # Style some cells! >>> spreadsheet["A2"].font = Bold_Font >>> spreadsheet["A3"].font = Big_Red_Text >>> spreadsheet["A4"].alignment = Center_Aligned_Text >>> spreadsheet["A5"].border = Square_Border >>> workbook.save(filename="sample_styles.xlsx") If you want to apply multiple styles to one or several cells in our spreadsheets,you can use  NamedStyle class: >>> from openpyxl.styles import NamedStyle >>> # Let's create a style template for the header row >>> header = NamedStyle(name="header") >>> header.font = Font(bold=True) >>> header.border = Border(bottom=Side(border_style="thin")) >>> header.alignment = Alignment(horizontal="center",vertical="center") >>> # Now let's apply this to all first row (header) cells >>> header_row = sheet[1] >>> for cell in header_row: ... cell.style = header >>> workbook.save(filename="sample_styles.xlsx") Adding Charts to our SpreadsheetCharts are a good way to compute and understand large amounts of data quickly and easily. We have a lot of charts such as bar chart, pie chart, line chart, and so on. Let us start by creating a new workbook with some data:  1 from openpyxl import Workbook   2 from openpyxl.chart import BarChart,Reference   3    4 workbook = Workbook()   5 spreadsheet = workbook.active   6    7 # Let's create some sample sales data  8 rows = [   9    ["Product","Online","Store"],  10    [1,30,45],  11    [2,40,30],  12    [3,40,25],  13    [4,50,30],  14    [5,30,25],  15    [6,25,35],  16    [7,20,40],  17 ]  18   19 for row in rows: 20    spreadsheet .append(row)Now let us create a bar chart that will show the total number of sales per product: 22 chart = BarChart() 23 data = Reference(worksheet=sheet, 24                 min_row=1,  25                 max_row=8,  26                 min_col=2,  27                 max_col=3)  28   29 chart.add_data(data,titles_from_data=True) 30 spreadsheet .add_chart(chart, "E2") 31 32 workbook.save("chart.xlsx")You can also create a line chart by simply making some changes to the data:  1 import random   2 from openpyxl import Workbook   3 from openpyxl.chart import LineChart,Reference   4    5 workbook = Workbook()  6 sheet = workbook.active  7    8 # Let's create some sample sales data   9 rows= [ 10    ["", "January", "February", "March", "April",  11    "May", "June", "July", "August", "September",  12     "October", "November", "December"],  13    [1, ], 14    [2, ], 15    [3, ], 16 ]  17   18 for row in rows:  19    sheet.append(row) 20   21 for row in sheet.iter_rows(min_row=2, 22                           max_row=4, 23                           min_col=2, 24                           max_col=13): 25    for cell in row: 26        cell.value = random.randrange(5,100)There are numerous types of charts and various types of customizations you can apply to your spreadsheet to make it more attractive.Convert Python Classes to Excel SpreadsheetLet us now learn how to convert the Excel Spreadsheet data to Python classes.  Assume we have a database and we use some Object Relational mapping to map the database into Python classes and then export the objects into spreadsheets: from dataclasses import dataclass from typing import List @dataclass class Sale: id: str  quantity: int @dataclass  class Product:  id: str  name: str  sales:List[Sale] Now, to generate some random data, let’s assume that the above classes are stored in  db_classes.py file then:  1 import random   2    3 # Ignore these for now. You'll use them in a sec ;)   4 from openpyxl import Workbook   5 from openpyxl.chart import LineChart,Reference   6    7 from db_classes import Product,Sale   8    9 products_range = []  10   11 # Let's create 5 products 12 for idx in range(1,6): 13    sales = []  14   15    # Create 5 months of sales  16    for_in range(5): 17        sale_range = Sale(quantity=random.randrange(5,100)) 18        sales.append(sale) 19   20    product = Product(id=str(idx), 21                      name="Product %s" % idx, 22                      sales=sales) 23    products_range.append(product)By running this code, we will get 5 products in 5 months of sale with a random quantity of sales for each month. Now, we have  to convert this into a spreadsheet in which we need to iterate over the data: 25 workbook = Workbook()  26 spreadsheet = workbook.active  27 28 # Append column names first  29 spreadsheet.append(["Product ID","Product Name","Month 1",  30              "Month 2","Month 3","Month 4","Month 5"])  31   32 # Append the data  33 for product in products_range: 34    data = [product.id,product.name] 35    for sale in product.sales: 36        data.append(sale.quantity)  37    spreadsheet.append(data) This will create a spreadsheet with some data coming from your database. How to work with pandas to handle Spreadsheets?We have learned to work with Excel in Python because Excel is one of the most popular tools and finding a way to work with Excel is critical. Pandas is a great tool to work with Excel in Python. It has unique methods to read all kinds of data in an Excel file and we can export items back to Excel using it. To use it, at first we need to install pandas package: $ pip install pandas Then, let’s create a simple DataFrame:  1 import pandas as pd   2    3 data = {   4    "Product Name":["Product 1","Product 2"],   5    "Sales Month 1":[10, 20],   6    "Sales Month 2":[5, 35],   7 }   8 dataframe = pd.DataFrame(data)Now we have some data, and to convert it from a DataFrame into a worksheet we generally use .dataframe_to_rows(): 10 from openpyxl import Workbook 11 from openpyxl.utils.dataframe import  dataframe_to_rows  12   13 workbook = Workbook()  14 spreadsheet = workbook.active  15   16 for row in dataframe_to_rows(df, index=False,header=True):  17    spreadsheet .append(row) 18   19 workbook.save("pandas_spreadsheet.xlsx")We need to use  read_excel method to read data from pandas DataFrame object. excel_file =’movies.xls’  movies=pd.read_excel(excel_file) We can also use Excel file class to use multiple sheets from the same excel file: movies_sheets = [] for sheet in xlsx.sheet_names:     movies_sheets.append(xlsx.parse(sheet))     movies = pd.concat(movies_sheets))Indexes and columns allows you to access data from your DataFrame easily: >>> df.columns  Index(['marketplace', 'customer_id', 'review_id', 'product_id',        'product_parent', 'product_title', 'product_category', 'star_rating',         'helpful_votes', 'total_votes', 'vine', 'verified_purchase',         'review_headline', 'review_body', 'review_date'],        dtype='object') >>> # Get first 10 reviews' star rating  >>> df["star_rating"][:10] R3O9SGZBVQBV76    5 RKH8BNC3L5DLF     5  R2HLE8WKZSU3NL    2  R31U3UH5AZ42LL    5  R2SV659OUJ945Y    4  RA51CP8TR5A2L     5  RB2Q7DLDN6TH6     5  R2RHFJV0UYBK3Y    1  R2Z6JOQ94LFHEP    5  RX27XIIWY5JPB     4  Name: star_rating, dtype: int64 >>> # Grab review with id "R2EQL1V1L6E0C9", using the index >>> df.loc["R2EQL1V1L6E0C9"] marketplace               US customer_id         15305006  review_id     R2EQL1V1L6E0C9  product_id        B004LURNO6  product_parent     892860326  review_headline   Five Stars  review_body          Love it  review_date       2015-08-31  Name: R2EQL1V1L6E0C9, dtype: object Summary In this article we have covered: How to extract information from spreadsheets  How to create Spreadsheets in different ways How to customize a spreadsheet by adding filters, styles, or charts and so on How to use pandas to work with spreadsheets Now you are well aware of the different types of implementations you can perform with spreadsheets using Python. However, if you are willing to gather more information on this topic, you can always rely on the official documentation of openpyxl. To gain more knowledge about Python tips and tricks, check out our Python tutorial. To gain mastery over Python coding,join ourPython certification course.  
Rated 4.5/5 based on 22 customer reviews
14108
How to Work with Excel Spreadsheets using Python

Excel is considered as one of the most popular and... Read More

20% Discount