Python Page – List of Posts

GUI Python Projects

This section is about using PyQT in order to design GUI application.

Encryption GUI App

PyQt Calculator Application Part 1

MatPlot Lib Tutorial

In this section we will be looking at how to use MatPlot to plot data and produce graphs for data analysis.

1: Plot series

2. Plot Vertical Bars

3. Plot Horizontal Bars

4. Plot Pie Charts

Project 1: PyQt – A small Calculator – Part 1

In this post we are going to create a small PyQt calculator application. Creating a calculator is always fun. So let’s start.

First of all I have used QT Designer to create the GUI that we need. Here below is the elements included in the GUI:

Qt Design – Our mycalc.ui file

As you can see we are using a gridLayout and adding 5 X 4 matrix of buttons for the very basic operations.

The button of Zero is called “p0”, the button 1 is called “p1” and so on.

The only control that is not a button is the “screen” that is in fact is a QPlainTextEdit called…..screen.

It is important to notice that the window is called calc.

Let’s save the file a mycalc.ui.

Now that we have a QT GUI file (mycalc.ui) we need to run from terminal the command to translate to Python code:

pyuic5 -x mycalc.ui -o

After running this command you will have a new file “”

If you open the file in the terminal you will see that it contains the main components in Python as show below :

The object name is “calc”. Buttons are listed together with the other control.

Python file for our small Calculator App

The file however does not do much : if you run it you will see the GUI application appearing on your screen however the application will not respond to the user inputs.If you press a button nothing will happen.

In order to have a real application responding to the user inputs we need to write another Python file. Of course the Python file is “interfaced” with the file. In other words one has all the controls in our GUI ( while the second one will determine what happens when one of these controls is activated (for example by clicking a button)

So let’s start coding a brand new open file.

We can start with a new class “MainWindow”.

class MainWindow(QMainWindow):

        def __init__(self,va1):
                super(MainWindow, self).__init__()
                self.ui = Ui_calc()

Apart from the va1 addition the rest of the line above are start for a MainWindow Application .

The class MainWindow will retrieve the elements of the UI_calc() class.

Other important part of the template is the bottom part which will launch the application:

app = QApplication(sys.argv)
w = MainWindow("")

Now that the template is set up we can actually start coding our application.

The first thing that we want to achieve is to connect each button with an event that will call in turn a function to show something (a number) in the screen: in other words if the user press the button p0 we want to display zero on the screen and therefore we will need to create a function to do so.

One way of doing this is by coding each button and associate buttons to an event (clicked) and connect it with a function specific function as shown below:

Coding each single control can be a very long and time consuming tak

One alternative approach is to use a for loop cycle to cycle through each button, associate it with an event clicked and connect it with the function.

In order to loop in the Main Window class we need to call a button that is part of the Ui_calc class.

Therefore we need to open the and add two list of buttons as shown below (one list for buttons 0-9 , the other one for all other buttons (+,-*,/, etc)

Creating 2 list of buttons in order to loop though the Main Application

The class Ui_calc has already each of these buttons as element of the class. The only thing we are doing is adding a variable called btn (type list) which included all the button from 0 to 9.

The same thing happens for the button sum,deduct, multiply, backwards,equal, point and cancel which are included a list called o.

So now because these buttons are part of the we can use them in our Python file to implement the loop

// This is a list of functions to display number 0-9

// This is another list of functions to do math operations

//First loop for button 0-9
for x in range(0,10):                     self.ui.btn[x].clicked.connect(self.inputNumber[x])
self.ui.btn[x].setStyleSheet(open('/home/piemex/Documents/Python/GUI/Calc Project/mystylesheet.css').read())

//Second loop for buttons for math operation
for x in range(0,8):
self.ui.o[x].setStyleSheet(open('/home/piemex/Documents/Python/GUI/Calc Project/mystylesheet.css').read())

//Set up a on/off button to start/shut down application
self.ui.ponoff.setStyleSheet(open('/home/piemex/Documents/Python/GUI/Calc Project/mystylesheet.css').read())

//Set Up Screen
self.ui.screen.setStyleSheet(open('/home/piemex/Documents/Python/GUI/Calc Project/mystylesheet.css').read())

In the code above we define a list (inputNumber) that is a collection of functions that we will use when buttons 0-9 are pressed. Each element of the list will activate its own function. So function zero will output zero on the calculator screen.

If the user press one button between 0-9 a corresponding button will be associate from the btn list of buttons that we have defined before.

Here is a comparison of declaring specfically each single button and looping through the list of buttons

A) self.ui.p4.clicked.connect(self.four)

B) self.ui.btn[x].clicked.connect(self.inputNumber[x])

inputNumber[x] is a list of functions : so if a press 4 the number 4 will be passed to the list inputNumber and retrive the funcion associated with that key

With the loop we are much more efficient because all we need is to put a number to the btn list rather than writing each single line.

We repeat the same operation for all buttons associated to a math operation (+,-,*,/ etc) in the second loop.

Let’s check the result once we run the application

Now that we have customize GUI with buttons that call an event we can describe better what happens if we press one button (for example five): in this file the function . So for example let’s say the user wants to multiply 125 * 2. He has already pressed 1 and then 2 and now press the button 5 or key the number five on the keppad. The corresponding function (five) will be called

def five(self):
                 self.va1= self.va1 + "5"

First the function findme will be called.

This function will look at the string in the screen and store it in the variable x. The the string will be searched for an equal sign. If this string includes the sign “= ” the variable y will be greater than -1. That means that an operation has already done previously and that we need to clear the screen and set out variable va1 equal to empty string.

def findme(self):
                if y>-1:

Let’s go back to our five function and suppose that we have do not have any equal sign in the string shown in the screen (so we have not yet told the calculator the whole operation) : in that case the current output shown in the screen will be contacted with the char 5. So we we had pressed 1 and 2 and then we press five the screen will show 125.

Now that we have 125 shown in our screen we want to multiply for 2 for example. So first we press the button multiply which will call the function multiply

def multiply(self):
                self.va1= self.va1 + "*"

The logic of each operator function (+,-,* and /) is a bit the same. The current string shown in the screen (va1) will be contacted with the operator sign and the output shown in the screen with the function screenme.

Now what happens when the equal operator is pressed?

Let’s check it out.

 def equal(self):
                result = 0
                result = eval(self.va1)
                self.ui.screen.insertPlainText("=" + str(result))

We set a variable result equal to zero. We use the eval function to evaluate the string 125* 2. This will return 250.

We move the cursor of the screen to the end and add the equal sign and then we convert the result to string. Finally we move the cursors to the end of the string again.

So now the screen will show 125*2 = 25

I will not describe each single function as at the bottom of the page you will find the link of the whole program.

One interesting aspect is that we want the calculator to work whether the user press with the mouse the button or key the number in the number keypad of the keyboard.

To do so we need to implement a function that listen to key being pressed on the keyboard

       def keyPressEvent(self,e):
                if e.key()==QtCore.Qt.Key_0:

In the above example the code of what happens when the user press zero. As you can see the function zero will be called.

Hope you have enjoyed this little tutorial on Python and QT.

Here is the full program available


Calculating how many days your are old

In this excercise we will learn about dates in Javascript, how to create an html tag using Javascript, how to set attribute for the new tag created (like setting an ID) and append it to an existing html element.

This function will start when the user press the button start.

First of all we start our JavaScript program by collecting the input from the user about the date. The prompt will ask the user to input the date in the format MM/DD/YYY

var x = prompt("Please Enter your birthdate as MM/DD/YYYY format");

In the next section of the code we will create two dates variable : the first one is based on the input provided by the user.

The second instead represent the current date

var birthdate = new Date(x);
var currentDate= new Date();

At this point we can calculate how many days are between 2 date with the following code

let numberOfDays = (currentDate-birthdate)/(24*60*60*1000);

Each day has 24 hours, 60 minutes, 60 seconds and each seconds is 1000 milliseconds.

Therefore we need to take the difference between current day and birthdate divide by the result of 24*60*60*1000.

We also want to avoid to display fraction of day and therefore we use the Math.Floor command round it to its floor value.

One other thing that we want to inform the user is in which day she/he was born.

To do this we use the function getDay(). However this function will return the number of day in the week.

If we want to know the day we need to run a small function that will return the name of the day

function returnmyDay(val1){
    //This function get the day you were born

    var weekday = new Array(7);
    weekday[0] = "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";
    var n = weekday[val1];
    return n;

The function above receive the number of day of the week as a parameter and then use the number provided to derive the corresponding day of the week.

Let’s have a look now at the html part of this program. We want the number of days and the day of birth displayed in the HTML page.

First of all we create to h3 tags with this command

var myh3 = document.createElement('h3');
var myh3b = document.createElement('h3');

Now that we have the h3 tag we need to assign it a unique ID so that we can bring in the message we want

 myh3.setAttribute('id','display data');
 myh3b.setAttribute('id','display data2');

So now the first tag will have an id “display data”. The second tag instead a “display data2″….sorry for the lack of creativity!

Now we can prepare the text message that we will display in the 2 tag h3 recently created:

var mytext = document.createTextNode('You are '  + result + ' days old');
var mytextb = document.createTextNode('You were born on ' + myday );

At this point we append the 2 text message to each h3 tag with the following command


So far we have attached the text to the Tag h3 but the tag does not have yet a place in the web page.

However if we look at the HTML code we have 2 container

So now we can attach the h3 tags to those 2 containers as shown below


You might recall that previously we have set attributes for each tag and created some id for the h3 tags. However so far we have not used those id. The id created is very handy for the clear button.

We want to have a button that clear the number of days and the day of the week. Let’s have a look at this function:

function clearall(){

    if (booleanchecker==true) {

    document.getElementById('display data').remove();
    document.getElementById('display data2').remove();
    document.getElementById('two').style.borderStyle = "none"; 
    document.getElementById('three').style.borderStyle = "none"; 

As you can see from the code above we are going to remove the h3 tag when the user press the button clear.

As we know that they have an id equal to display data and display date2 we can basically remove the tag h3 and by doing so the web page will no longer show the previous information.

The bookeanchecker is a global variable set to true at the beginning of the fucntion.

The clearall function will work only if the booleanchecker is true.: this will prevent an error in case in the user press twice in a row the clear button that will call the clearall function.

JavaFX Math Game

Let’s make a simple math game using JAVAFX program. This is an ongoing project so I will add more functionalities in futures post.

Here is the interface that we want to develop using JAVAFX:

The interface is composed by 3 Labels (in Aquamarine color) one TextField object and one Button.

Moving down we have one simple Label and another TextField to show the user the current score.

The Layout in JavaFX is a Flow Layout: this means that all controls(Buttons, Labels and TestFields) will be placed horizontally and if others controls do not fit the GUI Interface they will be showed below the first row of controls.

The Flow Layout is quite a useful Layout Schema to arrange Buttons, Labels and other controls.

As usual the complete program will be available in a link at the bottom of this page. Here for brevity we will discuss the key elements of the program

FlowPane mybox = new FlowPane();
mybox.setPadding(new Insets(40,40,40,40));
Scene myscene = new Scene(mybox,640,260);
stage.setTitle("My Math Game");

We start declaring what type of Layout is, we define padding space between the difference controls.

Then we declare a new Scene and we add the scene to the Stage as represented in the line above.

Now that we have the main framework of the Application we start defining the major controls like below:

label one = new Label();
one.setFont(new Font(36));
one.setStyle("-fx-border-color:blue; -fx-background-color: aquamarine;");

Line 3 of the above block it is important : in JAVAFX you can use CSS file type in order to customize the control (function setStyle access CSS string to format the JAVAFX Control)

At this point we set all the others control for our Math Game

Math Game GUI

All controls are added to the Scene using this command


Now the the GUI is explained let’s see what happen when the user press the Confirm Button (confirm)


As you can see when the button is pressed a function printme is called. We pass to the function:

Label one (first number)

Label two (math sign)

Label three (second number)

Label showScore (which report the level of the game)

Label yourScore (which show the actual score)

Label endgame (a label set to not visible)

Button (confirm – this button will get disable if the game is over)

The scope of the function printme is to retrieve the value from the GUI and verify whether the result is correct or not.

To values stores in each control are type String and therefore we need to cast it in integer

		int e1=Integer.parseInt(one.getText());
		int e2=Integer.parseInt(three.getText());
		int myresult =Integer.parseInt(four.getText());

Then we need to retrieve the sign of the operation (in the example below the code to test if the sign is equal to “+”

If that is the case we retrieve the value from the labels and check if the sum of the 2 values equals the input provided by the user

if (two.getText().equals("+")) {
if (e1+e2==myresult) {

If that is the case test is passed and therefore we can clear the TextField


and we also increase the score variable totalcounter : This is a public variable for the class accessible by all functions of the class


Then we have to generate 2 randoms number of the next question. We do that by calling the function genRandomNumber(one,two,three)

We have seen what happens if the user put the right answer. But what happens if the user put the wrong one?

If the test is failed we deduct the score with 5 points and set TextField with Red background color

if (e1+e2!=myresult) {
		four.setStyle("-fx-control-inner-background: red;");

But let’s go back and assume that the user put the right answer.

We call a function called genRandomNumber.

As you can see this function accepts 3 arguments (label one for the left number, label three for the second number and label two of the mathematical sign of the operation.

This function will generate

  1. Two random numbers
  2. One random number between 1 and 3 in order to select the math operation “+” or “-” or “*”
public void genRandomNumber(Label one,Label two,Label three) {
		Random r = new Random();
		int result = r.nextInt((max-min)+1)+min;
		result = r.nextInt((max-min)+1)+min;

The label one and three are both re-set showing the random number generated. The following part of the function will generate a random number between 1 and 3 and update label 2 with the corresponding sign

result = r.nextInt((maxsign-minsign)+1)+minsign;
		if (level2==true) {
		if (result==1) {
		else if (result==2) {
		else {

As you might have noticed in the block above there is one condition relating level2. If the user has achieved the level 2 all operations will be multiplication to make it more challenging (this is achieved by setting result equal to 1).

level2 is another class variable type boolean that is used to test if the user has achieved the most difficult level. In order to check the current level there is another function that is called levelchecker()

Here is the function:

public void levelchecker() {
		if ( (totalcounter>=8) && (level1==false) ) {
			max = max + 4;
			min = min + 4;	
			levelDesription="Level 1";
		if ( (totalcounter>=16) && (level2==false) ) {
			max = max + 8;
			min = min + 4;	
			levelDesription="Level 2";
		if ( (totalcounter>=24) && (level2==false) ) {
			max = max + 4;
			min = min + 3;	
			levelDesription="Level 2";

This function will be called any time the user input a correct answer to check the total number of points stored in the totalcounter variable.

If the points are between greater and 8 and the Level 1 has not been achieved yet the code will set the level1 equal to True and increase the class variable of 4 units each. So everytime a random number is generated the range of random number will pass from (0-20) to (4-24). This in fact will increase the complexity of the computation.

Once the next level is achieved there is not way to descend down to the more easier level because the boolean variable has been already turned equal to true. Therefore if I have 9 points and move to Level1 but if in the next question I make a mistake I will have only 5 points but I will stay in the Level 1 and not to regress to Level 0. Same thing happens for the other 2 levels

What happens if making a mistake brings negative the number of points? Well in that case GAME is OVER!

Let’s check how we do that:

if (totalcounter<=0) {
			endgame.setText("GAME OVEER!!!!!!");

As you can see we will do 2 things: disable the confirm button using setDisable and set visible the GAME OVER label using the command endgame.setViisble(true)

For example i am in Level 1 and I have only 4 points. I introduce a wrong answer -5 points : Game is Over.

In this link here the source code of the program.

This little project is not over yet. I will add few functionalities in the fortcoming days.

JAVA Programming

This section of the Blog is for Java. Java in my view is a really intesting language. It is full of libraries to basically do anything.

Java is a commonly used for Android Application but also for Enterprise Application.

I can run as a web application and it is portable to many operating systems.

The structure of the Language is not too different from C or C++ although there are main differences in term of architecture and memory management.

Current Project:

Project 1 : JavaFX Math Game