Search

Series List 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

5979
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

Scala Vs Kotlin

Ever-changing requirements in coding have always been happening, ones that cause programmers to change their minds about using the appropriate programming language and tools to code. Java has been there for a long time, a really long time, 24 years ago. It is relatively easy to use, write, compile, debug, and learn than other programming languages. However, its certain inhibitions like slow performance, unavailability of any support for low-level programming, possessing poor features in GUI 4, and having no control over garbage collection is putting Java developers in a dilemma on choosing an alternative to Java, such as JetBrains’ programming language, Kotlin, presently an officially supported language for Android development or Scala, an all-purpose programming language supporting functional programming and a strong static type system. Today, we will discuss how developers can decide to choose Scala or Kotlin as an alternative to Java. We will briefly talk about Scala and Kotlin separately and talk about their application before moving forward to looking at the differences, advantages, and disadvantages of both and finally have you decide which one of these two suits your requirements. User’s requirement Before we begin, here is a question for the readers, ‘What are you looking for in the next programming language that you will use?’ It is an obvious question because the programming purposes drive the actual basis and need of developing a language. Do you need a language that strives to better Java or use a language that lets you do things that aren’t possible in Java? If it is the first reason, then Scala might be the best one for you, otherwise, it is a simplified programming language like Kotlin. Now let us first briefly discuss Scala and Kotlin individually. ScalaDeveloped by Martin Odersky, the first version of Scala was launched in the year 2003 and is a classic example of a  general-purpose, object-oriented computer language, offering a wide range of functional programming language features and a strong static type system. Inspired from Java itself, Scala, as the name suggests, is highly scalable and this very feature sets Scala apart from other programming languages. When we say that Scala is inspired from Java, that means developers can code Scala in the same way they do for Java. Additionally, Scala makes it possible to use numerous Java and libraries within itself as well. It is designed to be able to use an elegant, concise and type-safe method to express common programming patterns. Scala is a very popular programming language amongst developers and rising up its ranks in the world of technology. Although Scala comes with a number of plus points, there are some which make it a bit ineffective. Here are the strengths and weaknesses of Scala. Strengths: Full Support for Pattern Matching, Macros, and Higher-Kinded Types Has a very flexible code syntax Gets a bigger Community Support Enables overloading operators Weaknesses: Slow in compilation Challenging Binary Compilation Not so proficient in the Management of Null SafetyKotlin Developed by JetBrains, Kotlin was released on February 2012 as an open-source language. Until now, there have been two released versions with the latest one being Kotlin 1.2, the most stable version that was released on November 28, 2017. Since Kotlin is extremely compatible with Java 6 the latest version of Java on Android, it has gained critical acclaim on Android worldwide and additionally, it offers various key features that are prepared only for Java 8 and not even Java 6 developers have access to that. Kotlin provides seamless and flawless interoperability with Java. That means, developers can easily call Java codes from Kotlin and same goes the other way around. The built-in null safety feature avoids showing the NullPointerException (NPE) that makes developing android apps easy and joyful, something every android programmer wants. Below mentioned are the key pointers on the strengths and weaknesses of Kotlin. Strengths Takes a Functional Programming Approach and Object-Oriented Programming style(OOP) Style  Has Higher-Order Functions Short, Neat, and Verbose-Free Expression  Supported by JetBrains and Google. Weaknesses: More limited Pattern Matching Additional Runtime Size Initial Readability of Code Shortage of Official Support Smaller Support Community. Ease of learning: Scala vs Kotlin Scala is a powerful programming language packed with superior features and possesses a flexible syntax. It is not an easy language to learn and is a nightmare for newcomers. Kotlin, on the other hand, has been reported to have been an easy-to-learn language for many Java developers as getting started with Kotlin is relatively easy and so is writing codes. Even though it is a comparatively easier language to learn and code with, Kotlin lacks the solid set of features that is common in Scala. It might take less time to learn a programming language, but the most important thing to look for is a comprehensive array of features. Scala, even though a very difficult language to learn, is cherished by the developers as it lets them do things that cannot be done in Kotlin Here are the major differences between Scala and Kotlin: ScalaKotlinType inferenceEfficientImmutabilityExtension FunctionsSingleton objectMassive InteroperabilityConcurrency controlLessens Crashes at RuntimeString interpolationSmart Cast FunctionHigher-order functionSafe and ReliableCase classes and Pattern matching Lazy computationLow adoption costRich collection setMaking the appropriate choice of languageNow, whether you may like a programming language or not, if that very language helps you get the best out of your job, then you will have to live with it. These are the facts about getting the best results. The outcome is the main factor in you deciding the appropriate language for your job. Kotlin is the only option for Android development as Android doesn’t use JVM, so any old JVM-compatible language will not work in Android. Kotlin has it all what it takes to compile, debug, and run the software on Android because of which it is in-built into Android Studio. However, Kotlin is not so usable outside Android development. If you are one of the developers who like working with Eclipse for your IDE, then Scala IDE is better than the Kotlin Plugin even if you can make Eclipse work with both the languages with limitations. Scala IDE is more advanced than the Kotlin plugin and is easier to set up. Some developers found it quite difficult to make the Kotlin plugin work. This case is quite the same with NetBeans. Kotlin is still getting there but is already popular amongst Java developers as it offers an easier transition than Scala. Kotlin is still maturing, but many Java people find adopting it is an easier transition than Scala is.  Scala, however, is for developers who are focused more on discovering new ideas while Kotlin is for those who want to get results. Kotlin stresses fast compilation but is more restrictive while Scala gives a lot of flexibility. Go for Scala if you breathe functional programming! It has more appropriate features for this type of programming than Kotlin does. Scala supports currying and partial application, the methods of breaking down functions requiring multiple arguments offering more flexibility. Go for the one that is the most appropriate one for your work, style of working and what you are aiming at. Think before you leap. The Outcome At the end of the day, all that matters is what you want to use the language for. While Scala goes well for the projects that require a combination of functional, OOP style programming languages, and where programmers need to handle lots of data or complex modelling, Kotlin becomes the best choice when you want something less frustrating than Java while developing apps because using Kotlin makes app development less cumbersome and a great thing to work on. It is just like a better-looking version of Java with less lengthy codes. 
Rated 4.5/5 based on 19 customer reviews
7590
Scala Vs Kotlin

Ever-changing requirements in coding have always b... Read More

Xcode vs Swift

Xcode and Swift are two different products developed by Apple for macOS, iOS, iPadOS, watchOS, and tvOS. While Xcode is an integrated development environment (IDE) for macOS containing a suite of software development tools to develop software for macOS, iOS, iPadOS, watchOS, and tvOS, Swift is a general-purpose, multi-paradigm, compiled programming language developed iOS, macOS, watchOS, tvOS, Linux, and z/OS. So it is clear that they can not be compared with each other. On the contrary, Swift is compatible with Xcode as Swift v 5.1, the default version of Swift is included in Xcode v 11. In this article, we will go through what Xcode and Swift are in general and cover their features strengths and weaknesses followed by how Swift is compatible with Xcode. XcodeIt was first released in 2003 as version 1 with the latest stable one being version 10.2.1 released on 17 April 2019. It can be downloaded from the Mac App Store and is free to use for macOS Mojave users. Registered developers may download the preview releases and previous versions of the suite using via the Apple Developer website.  Overview of the major featuresSupport: Programming languages such as C, C++, Objective-C, Objective-C++, Java, AppleScript, Python, Ruby, ResEdit (Rez), and Swift are supported by Xcode with source code along with support for a variety of programming models including Cocoa, Carbo, and Java. Not only that, there is additional support via third parties for GNU Pascal, Free Pascal, Ada, C#, Perl, and D Capability: Xcode can build fat binary files that include the code for various architectures in the Mach-O executable format. Known as universal binary files, these allow the application to run on both PowerPC and Intel-based (x86) platforms including both 32-bit and 64-bit codes Compiling and debugging: Xcode uses the iOS SDK to compile and debug applications for iOS that run on ARM architecture processors GUI tool: Xcode comprises of the GUI tool, Instruments that runs dynamic tracing framework on the top of DTrace, a dynamic tracing framework designed by Sun Microsystems and released as a part of OpenSolaris. Advantages and disadvantages of Xcode: Xcode is designed by Apple and will only work with Apple operating systems: macOS, iOS, iPadOS, watchOS, and tvOS. Since its release in 2003, Xcode has made significant improvements and the latest version, Xcode 10.2.1 has all the features that are needed to perform continuous integration. Let us have a look at the pros of using Xcode: Equipped with a well designed and easy to use UI creator Excellent for code completion Using Xcode, a developer can learn profiling and heap analysis in a natural way Xcode’s simulator lets you easily test your app while you build it in an environment that simulates your iPhone The app store has a wide range of audience who are willing to pay for apps. Now, the cons: Clunky and outdated Objective C makes it more frustrating if you are habituated to use a modern language No support for tabbed work environments makes it difficult to work with multiple windows Hardly any information can be found online to solve problems due to a previous Apple NDA on Xcode development It is a complicated process to export your app onto a device Will only work with Apple operating systems The App Store approval process can be annoyingly lengthy.SwiftSwift was launched at Apple's 2014 Worldwide Developers Conference as a general-purpose, multi-paradigm, compiled programming language for iOS, macOS, watchOS, tvOS, Linux, and z/OS Being a new entry these operating systems, Swift accelerates on the best parts of C and Objective C without being held back by its compatibility. It utilises safe patterns for programming, adding more features to it, thus making programming easier and more flexible. By developing their existing debugger, compiler and framework infrastructure, it took quite some time to create the base for Swift. Furthermore, Automatic Reference Counting was used to simplify the memory management part. The framework stack which was once built upon a solid framework of Cocoa and Foundation has undergone significant changes and is now completely regulated and refurbished. Developers who have worked with Objective-C do find Swift quite similar. Objective-C’s dynamic object model and its comprehensively named parameters provide a lot of control to Swift.  Developers can use Swift to have access to the existing Cocoa framework in addition to the mix and match interoperability with an objective C code. Swift uses this common rule to offer multiple new features in combination with object-oriented and procedural portions of the language. The idea is to create the best possible language for a wide range of uses, varying from desktop and mobile apps, systems programming, and scaling up to cloud services. The designing of Swift was done to make sure that developers find it easy to maintain and write correct programs. Coding done in Xcode is safe, fast and expressive. Swift offers a host of features that give developers the control needed to make the code easy to read and write. Furthermore, Apple made Swift to be easily understandable to help developers avoid making mistakes while coding and make the code look organised, along with the modules that give namespaces and eliminate headers. Since Swift uses some features present in other languages, one of them being named parameters written with clean syntax that makes the APIs much easier to maintain and read. Here are some of the additional features of Swift: Multiple return values and Tuples Generics Short and quick iterations over a collection or range Structs that support extensions, methods and protocols Functional programming patterns Advanced control flow Powerful error handling. These features are systematically designed to make them work together resulting in creating a powerful but fun-to-use language. Advantages and disadvantages of Swift: Pros of using the Swift Programming language: Easy to read and maintain: The Swift program codes are based on natural English as it has borrowed syntaxes from other programming languages. This makes the language more expressive Scalable: Users can add more features to Swift, making it a scalable programming language. In the future, Swift is what Apple is relying on and not Objective C Concise: Swift does not include long lines of code and that favours the developers who want a concise syntax, thus increasing the development and testing rate of the program Safety and improved performance: It is almost 40% better than the Objective-C when speed and performance are taken into consideration as it is easy to tackle the bugs which lead to safer programming Cross-device support: This language is capable of handling a wide range of Apple platforms such as iOS, iOS X, macOS, tvOS, and watchOS. Automatic Memory Management: This feature present in Swift prevents memory leaks and helps in optimizing the application’s performance that is done by using Automatic Reference Counting. Cons of Swift: Compatibility issues: The updated versions Swift is found to a bit unstable with the newer versions of Apple leading to a few issues. Switching to a newer version of Swift is the fix but that is costly Speed Issues: This is relevant to the earlier versions of the Swift programming language Less in number: The number of Swift developers is limited as Swift is a new programming language Delay in uploading apps: Developers will be facing delays over their apps written in Swift to be uploaded to the App Store only after iOS 8 and Xcode 6 are released. The estimated time for release is reported to be September-October, 2014. Conclusion So as we discussed both Xcode and Swift, it is clear that they cannot be compared to each other. In fact, they both complement each other to deliver impressive results without any headaches. Apple relies on both quite a lot and it is certain to have Swift and Xcode the perfect combination of a robust application and a user-friendly programming language.
Rated 4.5/5 based on 11 customer reviews
8588
Xcode vs Swift

Xcode and Swift are two different products develop... Read More

ASP.NET VS PHP

ASP.NET and PHP are pretty popular languages in the programming world used by a huge number of developers and this makes it difficult for the new developers to choose either one of them. The comparison between these two has been in debate in recent times. Both of these languages are used in large web-based applications. Some successful companies like Google, Facebook, and Twitter, etc, also use these languages. In this article, we will understand the differences between PHP and ASP.Net also, will discuss which is better ASP.NET or PHP.Before we learn more about the differences between the two languages, we must first understand some basics of the two technologies:PHPPHP stands for Hypertext Preprocessor. It is an open-source programming language that is used for web development and can be embedded into HTML. The best part of PMP is that it’s free and possesses a  ton of frameworks which simplifies web development and also great for beginners since it allows simple and easy coding techniques. PHP is great for professionals as well because of its advanced features.Why use a PHP framework?A PHP framework provides a basic structure for streamlining the development of web apps. The applications and websites built using PHP frameworks will help the businesses to improve their performance needs.The best PHP frameworks available:LaravelCodeIgniterSymfonyZendPhalconCakePHPYiiFuelPHPPros and Cons of PHP frameworkPros:Rapid Development                                              Centralized DatabaseStronger TeamworkMakes your application more secure               Cons:Slower ExecutionPHP is unsecuredPoor error handling methodLimited Visibility and ControlDemand for PHP Developer:In today’s web development market, most of the websites are developed using PHP development tools which indicates a huge demand for PHP developers. If you are looking to make an entry to the IT world as a developer, then PHP programming will be an easy entry point.Taking up a PHP training from an authentic and reliable training provider will be a great platform to hone your skills.ASP.NETASP.NET is an open-source server-side web development tool developed by Microsoft for easy building of web applications and web pages. It can be written using any .Net supported language which makes it more popular among .NET developers. High speed and low cost are the main reasons to use it. Websites built ASP.NET is faster and more efficient than a website built with PHP.Pros and Cons of ASP.NET frameworkPros:Less coding timeWorld class toolboxConsistencyCustomizability and ExtensibilityCons:Limited Object-Relational (OR) supportBit expensiveSlower than Native CodeDemand for ASP.NET Developer:If you are a .NET developer, you will find yourself demanded by several asp.net development companies as your programming skills are extremely valuable in today’s market. There are many companies hunting for developers who can do programming with .NET. Therefore, it is advisable that you brush up your skills with ASP.NET Certification Training which will increase your value many times and have an edge over others. The ASP.NET Certification Training program will definitely make your future bright and offer you heaps of career opportunities. Whether you are a fresher or a working professional, you can take up the certification course.Comparison Between ASP.NET and PHPBoth ASP.NET and PHP frameworks are effective frameworks to work with, however, one may have few advantages over the other. Let’s dive deeper and compare these frameworks to understand which one is better than the other.1. Market Share:According to the report, BuiltWith data source PHP is the most used programming language which has 73% of market share, ASP.NET has 23% of market share. PHP also has a market share of 58% in top 100K websites and market share of PHP in 10K websites is 52%.Statistics for websites using Programming Language technologies:2. WebsitesHere are two lists to compare ASP.NET vs PHP websites:Websites built using PHPWebsites built using ASP.NETWikipediaFacebookYahooWordPress.comiStockPhotoMicrosoftDellGoDaddy3. Inbuilt featuresPHP has many unique in-built features that can help web developers. On the other hand, ASP.NET doesn’t have any such features.4. Speed and PerformanceWhen you compare PHP vs. ASP.NET for speed, PHP will be the winner. ASP.NET is a bit slow compared to PHP as it is built on the COM-based system whereas, PHP program runs on its own memory space.5. Community SupportCompared to ASP.NET, learning support is great in the PHP framework and has a large support community. It will be difficult for you to get hold of #C language of ASP.NET as it is difficult to understand.Key differences between ASP.NET vs PHPPHPASP.NETPHP was launched by Rasmus Lerdorf in the year 1995.ASP.NET was launched by Microsoft in the year 2002.PHP is a scripting languageASP.NET is a paid Microsoft provided web application framework.PHP suits for small sized organizationsASP.NET suits for a large and medium-sized organization.PHP has a decent market share in the  marketASP.NET has a higher market sharePHP works slow for desktop applicationsASP.NET is well equipped to assist and create desktop applications.PHP suits best for applications that contain a prime focus on UIASP.NET suits better for applications where the key concern is security.Easy to learnQuite challenging to learn.Coding using PHP is easy when compared to all other languagesCoding with ASP.NET is complicatedPHP execution is faster since it uses in-built memory spaceCoding with ASP.NET is complicatedPHP can run in Linux Operating System which is available for freeASP.NET requires a Windows platform which is not freeConclusionBoth PHP and ASP.NET come with their pros and cons. PHP is secure, fast, reliable, and inexpensive and ASP.NET is easier to use and maintain because of its class library system. Since both programming languages are similar and accomplish the same results so the company can make a choice based on the needs and requirements of the app they are about to develop.
Rated 4.5/5 based on 1 customer reviews
7708
ASP.NET VS PHP

ASP.NET and PHP are pretty popular languages in th... Read More

20% Discount