Python Program to Add Two Numbers in Tkinter5 min read

It is a simple Python program to add two integers and display their sum. This program is only for learning Python Tkinter.
Here two text boxes will accept two numbers from user and display their sum in another text box.

Here is an example of a Python program that adds two numbers in Tkinter:


Python Program to Add Two Numbers in Tkinter
Python Program to Add Two Numbers in Tkinter

This program creates a simple GUI with two entry fields for the numbers and a button to trigger the addition. When the button is clicked, the add function is called, which gets the numbers from the entry fields, adds them, and displays the result in a label. The widgets are then laid out using the grid geometry manager.

Here is a brief explanation of the code:

This line imports the Tkinter module, which provides the interface to the Tk GUI toolkit. We import it under the alias tk for convenience.

This is the add function that is called when the “Add” button is clicked. It gets the values of the two entry fields using the get method, converts them to floats, adds them, and updates the text of the result label with the result.

This creates the main window and sets its title.

These lines create the widgets for the program. The labels and buttons are created with their respective constructors, and the entry fields are created with the Entry constructor. The command option of the button specifies the function to be called when the button is clicked.

These lines use the grid geometry manager to lay out the widgets in a grid. The row and column options specify the row and column of the grid that the widget should be placed in, and the columnspan option specifies how many columns the widget should span. The sticky option specifies how the widget should be aligned within its cell, and the pady option adds some padding to the bottom of the button.

This starts the main loop of the program, which listens for events such as button clicks and updates the GUI accordingly. This is what makes the GUI interactive.

I hope this helps to clarify things!

You also like this : Simple Calculator Example in Python 3 Tkinter

Alternative Example:


Code Behind Interface(python v3.8):

This code creates a simple graphical user interface (GUI) in Python using the Tkinter library.

The GUI consists of two Entry widgets (e1 and e2) that allow the user to input numbers, a Button widget (b) that runs a function when clicked, and a Label widget (result) that displays the result of the function.

When the Button is clicked, the addNumbers function is called. This function gets the text from the Entry widgets, converts them to integers, and adds them together. The result is then displayed in the Label widget by setting the textvariable to the result.

Finally, the mainloop function is called to start the Tkinter event loop, which handles all the events (like button clicks) and updates the GUI as necessary.


Leave a Comment