Creating a Basic Calculator Application Using Python Tkinter GUI Tutorial #5

Posted by


In this tutorial, we will be building a simple calculator app using Python’s Tkinter GUI library. Tkinter is a built-in library in Python that allows you to create GUI applications easily. This tutorial assumes that you have a basic understanding of Python programming and are familiar with the concepts of functions, variables, and basic GUI programming.

Step 1: Setting up the Environment
First, make sure you have Python installed on your system. You can download Python from the official website (https://www.python.org/). Once you have Python installed, you can start by creating a new Python file for your calculator app.

Step 2: Importing Tkinter Library
The first step is to import the Tkinter library in your Python script. You can do this by adding the following code at the beginning of your script:

from tkinter import *

Step 3: Creating the GUI Window
Next, you need to create the main window for your calculator app. You can do this by creating an instance of the Tk class, which represents the main window of your application:

root = Tk()
root.title("Simple Calculator")

Step 4: Adding the Display Widget
To display the numbers and results of the calculations, you will need to add a Text widget to your GUI window. You can do this by adding the following code:

display = Text(root, height=2, width=30, borderwidth=5, relief=RIDGE)
display.grid(row=0, column=0, columnspan=4, padx=10, pady=10)

This code creates a Text widget with a height of 2 lines and a width of 30 characters. It also sets the borderwidth to 5 and the relief to RIDGE, which gives the widget a raised appearance. Finally, the grid() method is used to place the widget in the main window.

Step 5: Adding Button Widgets
Next, you need to add the buttons for the numbers and operations in your calculator. You can do this by creating Button widgets for each button and placing them in the main window using the grid() method. Here’s an example code snippet for creating the number buttons:

buttons = [
    '7', '8', '9', '/',
    '4', '5', '6', '*',
    '1', '2', '3', '-',
    'C', '0', '=', '+'
]

row = 1
col = 0

for button_text in buttons:
    Button(root, text=button_text, width=5, height=2).grid(row=row, column=col, padx=5, pady=5)
    col += 1
    if col > 3:
        col = 0
        row += 1

This code creates a list of button labels and then iterates over each label to create a Button widget with the label text. The buttons are placed in rows and columns using the grid() method, with padding added for spacing between the buttons.

Step 6: Implementing Button Click Events
Now that you have the buttons added to your GUI window, you need to implement the functionality for each button. For example, when the user clicks on a number button, the corresponding number should be displayed in the Text widget. Similarly, when the user clicks on an operation button, the appropriate operation should be performed.

To do this, you can create a function that handles the button click events and updates the display accordingly. Here’s an example code snippet for implementing the click events:

def on_button_click(event):
    button_text = event.widget.cget('text')

    if button_text == '=':
        try:
            result = eval(display.get('1.0', END))
            display.delete('1.0', END)
            display.insert(END, str(result))
        except:
            display.delete('1.0', END)
            display.insert(END, 'Error')
    elif button_text == 'C':
        display.delete('1.0', END)
    else:
        display.insert(END, button_text)

for widget in root.winfo_children():
    widget.bind('<Button-1>', on_button_click)

This code defines a function on_button_click() that is called when a button is clicked. The function gets the text of the clicked button and performs the appropriate action based on the text. For example, if the button text is ‘=’, the function calculates the result of the expression in the Text widget and displays it. If the button text is ‘C’, the function clears the Text widget. Otherwise, the function inserts the button text into the Text widget.

Finally, the bind() method is used to bind the on_button_click() function to the click events of all the widgets in the main window.

Step 7: Running the Application
Once you have implemented all the necessary functionality for your calculator app, you can run the application by adding the following code at the end of your script:

root.mainloop()

This code starts the main event loop of the Tkinter library, which is responsible for handling user events, such as button clicks, and updating the GUI accordingly.

That’s it! You have now built a simple calculator app using Python’s Tkinter library. You can further customize the app by adding more features, such as memory functions, scientific operations, and themes. Feel free to explore the Tkinter documentation (https://docs.python.org/3/library/tkinter.html) for more advanced GUI programming concepts. Happy coding!

0 0 votes
Article Rating

Leave a Reply

20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Codemycom
1 hour ago

▶️ Watch Entire Tkinter Playlist ✅ Subscribe To My YouTube Channel:
http://bit.ly/2UFLKgj http://bit.ly/2IGzvOR
▶️ See More At: ✅ Join My Facebook Group:
https://Codemy.com http://bit.ly/2GFmOBz
▶️ Learn to Code at https://Codemy.com ✅ Buy a Codemy T-Shirt!
Take $30 off with coupon code: youtube1 http://bit.ly/2VC9WUN

@SaherAli-t3s
1 hour ago

Clark Steven Walker Michael Rodriguez Joseph

@chanero-u8z
1 hour ago

I just try it myself. In the end , the result is a little bad, but I have finish it.

@МаликаШангитова
1 hour ago

Hi, I have SyntaxError: positional argument follows keyword argument. why

@Hotwire_RCTrix
1 hour ago

So the bloody font doesn't vary from Lambda to lambda. Waste of 30 minutes.
So could you please explain want this does, now that it's used up time. I would have thought calling a command would have also included parameters, which deserves an explanation.

@SomeOne-ec9zx
1 hour ago

It's a wow what you are doing……..keep going

@aydnaydin9109
1 hour ago

hello someone can explain why we need lambda ?

@gpecs
1 hour ago

why is tkinter gui not loading automatically why do i need to re-run it everytime i make changes.

@gpecs
1 hour ago

Nice tutorials. Instead of running the code everytime, is there a way TK gui can automatic reload after saving in vscode?

@rodrigopharazz
1 hour ago

Thank You🙏

@tor6953
1 hour ago

Thank you

@abdolrezamohseni9787
1 hour ago

Awesome. Great teaching. Is there any chance to have access to the written codes for each of the video?

@janlochman1985
1 hour ago

Hey, why you have placed columnspan parameter and applied it on the Entry widget? The other (button) widgets inherit it?

@MajidHashemi-rt8le
1 hour ago

Thanks u🎉

@21no.8john9
1 hour ago

i wonder about lambda function , i never see to use function outside and use inside lambda , can anyone tell me how it work

@Algeriawindows69
1 hour ago

16:21 hey dude i got an error that always says "

e.delete( 0, END)

^^^^^^^^

AttributeError: 'NoneType' object has no attribute 'delete'

"
and even when i remove it another error pops
" e.insert( 0, number)

^^^^^^^^

AttributeError: 'NoneType' object has no attribute 'insert'"

@yeuduongtamhuong
1 hour ago

width and padx button, how different?

@erikdejong4509
1 hour ago

how to fix Tlc/Tk error

@user-ot6vw4nw6w
1 hour ago

sir my global variable aint working

@aneeshmadhavan2903
1 hour ago

How to make the tkinter window flexible when maximizing or adjusting the size of the window?

20
0
Would love your thoughts, please comment.x
()
x