How to Build Calculator in Python TKinter

In this lesson we want to learn How to Build Calculator in Python TKinter, Here is an example of a simple calculator built using the Tkinter library in Python:

 

This code creates a simple calculator using the Tkinter library in Python.

The Calculator class is a subclass of tk.Tk, which is the main window class of Tkinter. The __init__ method sets the title of the window to “Calculator” and sets its size to 200×200 pixels.

A text entry widget is created and added to the window using the tk.Entry class. This widget will be used to display the results of calculations.

The button_list variable is a list of strings that represent the buttons on the calculator. These buttons are then created and added to the window using a loop. Each button is created using the tk.Button class and is given a label, a width, a height, and a command to execute when clicked. The button_click method is used as the command for all buttons except the “=” button, which uses the calculate method as its command.

The button_click method is used to handle button clicks. If the button clicked is the “C” button, it clears the text in the result widget. If it’s any other button, it appends the button’s label to the text in the result widget.

The calculate method is used to evaluate the mathematical expression entered in the result widget. It uses the re.sub() function to remove any non-numeric or non-mathematical characters from the input, so that the eval() function only receives a well-formed mathematical expression. It then uses the eval() function to evaluate the expression and display the result in the result widget. If the input is not a valid mathematical expression or if any other error occurs, it displays “Error” in the result widget.

Finally, an instance of the Calculator class is created and mainloop() method is called on it, which starts the event loop and makes the calculator window visible on the screen.

 

 

Run the complete code and this will be the result.

How to Build Calculator in Python TKinter
How to Build Calculator in Python TKinter

 

 

Learn More on TKinter

Leave a Comment