Python comes bundled with several options for building graphical user interfaces (GUIs). The most common and easiest to use is Tkinter.
Tkinter is the standard Python interface to the Tk GUI toolkit. It ships directly with Python, so there are no additional dependencies needed. This makes Tkinter very accessible for beginners to start working with GUI programming.
Building a GUI with Tkinter involves a few main steps:
- Import the Tkinter Module
- Create the Main Window
- Add Widgets
- Layout Widgets
- Add Interactivity
Below is what the GUI looks like:
Below you will find the code implementation of this Tkinter calculator. We will define classes to organize the GUI elements and calculation logic. Buttons will trigger event handlers that update the display and run computations.
Some key aspects include laying out widgets in a grid, setting up callbacks, and designing an interface for fluid number entry and result viewing. By completeing this tutorial, you'll learn the fundamentals of building interactive programs with Tkinter in Python.
Let's begin by setting up our imports and classes. Then we can start adding buttons, wiring up click events and programming the calculation processing.
# import everything from tkinter module
from tkinter import *
# globally declare the expression variable
expression = ""
# Function to update expression in the text entry box
def press(num):
# point out the global expression variable
global expression
# concatenation of string
expression = expression + str(num)
# update the expression by using set method
equation.set(expression)
# Function to evaluate the final expression
def finalpress():
# for handling the errors like zero , division error and etc.
try:
global expression
# eval function evaluate the expression and str function convert the result into string
total = str(eval(expression))
equation.set(total)
# initialize the expression variable by empty string
expression = ""
# if error is generate then handle by the except block
except:
equation.set(" error ")
expression = ""
# Function to clear the contents of text entry box
def clear():
global expression
expression = ""
equation.set("")
# Driver code
if __name__ == "__main__":
# create a GUI window
gui = Tk()
# set the background colour of GUI window
gui.configure(background="black")
# set the title of GUI window
gui.title("Simple Calculator")
# set the configuration of GUI window
gui.geometry("260x150")
# StringVar() is the variable class
equation = StringVar()
# create the text entry box for
expression_field = Entry(gui, textvariable=equation)
# grid method is used for placing the widgets at respective positions in table like structure .
expression_field.grid(columnspan=4, ipadx=70)
# create a Buttons and place at a particular location inside the root window .
button1 = Button(gui, text=' 1 ', fg='black', bg='white',
command=lambda: press(1), height=1, width=7)
button1.grid(row=2, column=0)
button2 = Button(gui, text=' 2 ', fg='black', bg='white',
command=lambda: press(2), height=1, width=7)
button2.grid(row=2, column=1)
button3 = Button(gui, text=' 3 ', fg='black', bg='white',
command=lambda: press(3), height=1, width=7)
button3.grid(row=2, column=2)
button4 = Button(gui, text=' 4 ', fg='black', bg='white',
command=lambda: press(4), height=1, width=7)
button4.grid(row=3, column=0)
button5 = Button(gui, text=' 5 ', fg='black', bg='white',
command=lambda: press(5), height=1, width=7)
button5.grid(row=3, column=1)
button6 = Button(gui, text=' 6 ', fg='black', bg='white',
command=lambda: press(6), height=1, width=7)
button6.grid(row=3, column=2)
button7 = Button(gui, text=' 7 ', fg='black', bg='white',
command=lambda: press(7), height=1, width=7)
button7.grid(row=4, column=0)
button8 = Button(gui, text=' 8 ', fg='black', bg='white',
command=lambda: press(8), height=1, width=7)
button8.grid(row=4, column=1)
button9 = Button(gui, text=' 9 ', fg='black', bg='white',
command=lambda: press(9), height=1, width=7)
button9.grid(row=4, column=2)
button0 = Button(gui, text=' 0 ', fg='black', bg='white',
command=lambda: press(0), height=1, width=7)
button0.grid(row=5, column=0)
plus = Button(gui, text=' + ', fg='black', bg='white',
command=lambda: press("+"), height=1, width=7)
plus.grid(row=2, column=3)
minus = Button(gui, text=' - ', fg='black', bg='white',
command=lambda: press("-"), height=1, width=7)
minus.grid(row=3, column=3)
multiply = Button(gui, text=' * ', fg='black', bg='white',
command=lambda: press("*"), height=1, width=7)
multiply.grid(row=4, column=3)
divide = Button(gui, text=' / ', fg='black', bg='white',
command=lambda: press("/"), height=1, width=7)
divide.grid(row=5, column=3)
equal = Button(gui, text=' = ', fg='black', bg='white',
command=finalpress, height=1, width=7)
equal.grid(row=5, column=2)
clear = Button(gui, text='Clear', fg='black', bg='white',
command=clear, height=1, width=7)
clear.grid(row=5, column='1')
Decimal= Button(gui, text='.', fg='black', bg='white',
command=lambda: press('.'), height=1, width=7)
Decimal.grid(row=6, column=0)
# start the GUI
gui.mainloop()
Here is a detailed description of the code :
1. Importing Libraries: The code starts by importing everything from the Tkinter module, which provides the necessary functionality for creating GUI applications.
2. Global Variable: The variable `expression` is declared as a global variable. It will store the mathematical expression entered by the user.
3. Function to Update Expression: The `press(num)` function is defined to update the `expression` variable when a button is pressed. It appends the pressed number or operator to the `expression` string and updates the text displayed in the text entry box.
4. Function to Evaluate the Expression: The `finalpress()` function is responsible for evaluating the final expression entered by the user. It uses the `eval()` function to evaluate the expression as a Python expression and converts the result to a string. The evaluated result is then set as the value of the `equation` variable, and the `expression` variable is reset to an empty string.
5. Function to Clear the Contents: The `clear()` function is used to clear the contents of the text entry box. It sets the `expression` variable to an empty string and updates the value of the `equation` variable accordingly.
6. GUI Setup: The code then sets up the GUI window by creating an instance of the `Tk` class and configuring the window's properties such as the background color, title, and size.
7. StringVar: The `equation` variable is created as an instance of the `StringVar` class. It is used to store and update the text displayed in the text entry box.
8. Text Entry Box: The `expression_field` is created as an `Entry` widget, which provides a text entry box for the user to input the mathematical expression. The `textvariable` parameter is set to the `equation` variable, so any changes to the `equation` variable will automatically update the contents of the text entry box.
9. Buttons: Various buttons are created using the `Button` widget. Each button represents a number, operator, or special function (such as equal, clear, or decimal point). The `text` parameter sets the label of the button, and the `command` parameter assigns a function to be executed when the button is clicked. The buttons are arranged in a grid using the `grid` method, specifying the row and column positions.
10. Main Loop: Finally, the `mainloop()` method is called, which starts the GUI event loop, allowing the user to interact with the calculator. The program will continue to run until the user closes the window.
In summary, this post provides a detailed guide on building a simple calculator GUI using Tkinter in Python. It covers the steps to set up the GUI window, create widgets, and define event handlers. The calculator allows users to perform basic arithmetic operations.
If you have any comments or questions regarding the tutorial or if you would like to suggest any improvements or topics for future posts, please feel free to leave your feedback. Your input is valuable and helps us provide content that is relevant and helpful to our readers.
0 Comments