<img height="1" width="1" src="https://www.facebook.com/tr?id=1101141206686180&amp;ev=PageView &amp;noscript=1">

Making a calculator with Pyside

Python is not really the first language that comes to mind when thinking about GUI development. However, it is a great tool for automating all types of workflows. There can be certain use cases when a sort of UI integration can really help in automation. Lately, I have been using PySide as my choice of a python UI library. It is built off the Qt framework and is free to use. For today, I thought it would make a fun blog post to create a basic GUI math calculator in PySide for those interested in learning some of the syntax.

Here is the basic Hello World. I created a class that represents the main window, set some parameters like the size and the title, and then added a layout with a label. Think of the layout as a container for all the other components.

ss_snippet_1

pic_1

Now I need to create some buttons and put them in a QGridLayout. I decided to create two more classes to keep the MainWindow class a bit cleaner. The first class will be what all my buttons will be based off.


The second class just builds off the QGridLayout and my StdButton class to make the grid of buttons like a real calculator. I use a loop to create the numbers but manually add the rest of the buttons. I’m sure this could be refactored to look cleaner.


I created a globally scoped function to test the button clicked signal.

StdButton_Comment

testFunc

 

The next step is to make the digital indicator that creates the above the buttons. For this, I am making another class that will simply consist of a styled QLabel. I will add it to the main window class.

NumGrid_Comment

I now need a way to update the indicator every time a button is pressed. I will define 3 functions to do this. Do_math will be used to perform the basic arithmetic. The function get_op will be used to parse which option I need to use when calling do_math. The function handle_click will be used to modify the string I show in the indicator. To make things simple, I treat all the operators as an ‘=’ if I already have one in the indicator.

Math_comments

 

I never added support for the positive/negative button. If you found this interesting and would like to learn more, I challenge whoever read to the end,  to add support for the last button. You can free the entire source on my GitHub page. https://github.com/AshtonScalise/pyside-calculator

 

Below is the final product of the calculator.

final