<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ GUI - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ GUI - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 26 Jun 2026 22:46:59 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/gui/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Calculator with Tkinter in Python  ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, you'll learn how to create a simple arithmetic calculator in Python with Tkinter. The project will be one of your first steps towards building an actual GUI in Python. This is a hand ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-a-calculator-with-tkinter-in-python/</link>
                <guid isPermaLink="false">6a07203c99d875f5cd667635</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GUI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tkinter ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Sara Jadhav ]]>
                </dc:creator>
                <pubDate>Fri, 15 May 2026 13:31:40 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5fc16e412cae9c5b190b6cdd/0ae14c91-3e47-464c-b392-1026321a7764.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, you'll learn how to create a simple arithmetic calculator in Python with Tkinter. The project will be one of your first steps towards building an actual GUI in Python.</p>
<p>This is a hands-on tutorial, which will help you form your early GUI projects. It's meant for anyone who wants to start building visual projects in Python.</p>
<p>The Tkinter library is a standard built-in Python library which helps us make Graphical User Interfaces in Python. Since it's a built-in library, we don't have to separately install it. So, once you have Python installed on your computer, you just have to set it up and you're good to follow along here.</p>
<p>But keep in mind that Tkinter may not be installed with your Python from the distributor end. To check if it's installed or not, open your command prompt and type:</p>
<pre><code class="language-plaintext">python -m tkinter
</code></pre>
<p>This will open up a Tkinter specimen window if Tkinter is installed and working on your computer.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-what-do-we-want-to-see-in-our-project">What Do We Want to See in Our Project?</a></p>
</li>
<li><p><a href="#heading-how-to-set-up-the-window">How to Set Up the Window</a></p>
</li>
<li><p><a href="#heading-how-to-name-the-window">How to Name the Window</a></p>
</li>
<li><p><a href="#heading-how-to-create-frames-in-the-window">How to Create Frames in the Window</a></p>
</li>
<li><p><a href="#heading-how-to-add-buttons-to-the-window">How to Add Buttons to the Window</a></p>
</li>
<li><p><a href="#heading-how-to-add-the-output-screen-of-the-calculator">How to Add the Output Screen of the Calculator</a></p>
</li>
<li><p><a href="#heading-how-to-make-the-numbers-visible-on-the-output-screen">How to Make the Numbers Visible on the Output Screen</a></p>
</li>
<li><p><a href="#heading-how-to-add-a-scrollbar-to-the-output-screen">How to Add a Scrollbar to the Output Screen</a></p>
</li>
<li><p><a href="#heading-how-to-add-the-equal-to-button">How to Add the Equal To Button</a></p>
</li>
<li><p><a href="#heading-how-to-add-the-ac-button">How to Add the AC Button</a></p>
</li>
<li><p><a href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before starting, here are some prerequisites for this tutorial which will help you get the most out of it:</p>
<ul>
<li><p>Basic Python Syntax</p>
</li>
<li><p>Understanding of how to import and use libraries and its different functions</p>
</li>
<li><p>Understanding of how to use different attributes of the module</p>
</li>
</ul>
<p>Now that we know what we need to proceed in this tutorial, let's actually dive-in the process!</p>
<p>The first step for building any project is to create a clear-cut idea of what you want to build. Let's look at what we're going to make.</p>
<h2 id="heading-what-do-we-want-to-see-in-our-project">What Do We Want to See in Our Project?</h2>
<p>We're going to build a simple arithmetic calculator. The calculator works as follows:</p>
<ul>
<li><p>It has all the numerals (0, 1, 2, ...., 9) in a keyboard.</p>
</li>
<li><p>It has basic arithmetic (+, -, /, *, =) operators lining the keyboard.</p>
</li>
<li><p>The calculator is non-resizable, that is the user can't extend the width or the height of the application window.</p>
</li>
<li><p>The calculator has a screen above the keyboard which shows the user input and the final answer.</p>
</li>
<li><p>Finally, the calculator has an 'AC' button which stands for 'All Clear' which erases everything on the output screen of the window and allows the user to use it again.</p>
</li>
</ul>
<p>With this, we have a clear idea about what we're going to build.</p>
<p>Also, you can create the UI beforehand and place the widgets accordingly on the window. Here's an image of the UI we'll create in this tutorial:</p>
<img src="https://cdn.hashnode.com/uploads/covers/67e55054a0be57d730442ec0/93d8458d-f829-4edb-9651-622a14f9444a.png" alt="UI of the calculator " style="display:block;margin:0 auto" width="249" height="388" loading="lazy">

<h2 id="heading-how-to-set-up-the-window">How to Set Up the Window</h2>
<p>To set up our main window where we'll later add our widgets, first we need to import the Tkinter library into our program. Then we'll initialize the window using the <code>tk.Tk()</code> function. To display the window on the screen continuously until we quit manually, we'll use the <code>mainloop()</code> function. Here's what the code looks like:</p>
<pre><code class="language-python">import tkinter as tk

# screen initialization
root = tk.Tk()

# This keeps the window active
root.mainloop()
</code></pre>
<p>The<code>root</code> variable represents our window. So, from now on, we'll be adding the widgets to this window.</p>
<p>When a user hits "Run", you'll see a blank window on your screen as shown in the image below. Congrats! This is your first GUI.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67e55054a0be57d730442ec0/ee60f1d8-ea5b-415d-96bf-90941ecd9424.png" alt="Blank tkinter window " style="display:block;margin:0 auto" width="214" height="241" loading="lazy">

<h2 id="heading-how-to-name-the-window">How to Name the Window</h2>
<p>The 'tk' written on the Title Bar is the default title of the window. To set our own window title, we can use the <code>title()</code> function. The following code shows how you can do that:</p>
<pre><code class="language-python">import tkinter as tk

root = tk.Tk()

# Naming the window
root.title("Calculator")

root.mainloop()
</code></pre>
<p>On executing the program, we get the following window:</p>
<img src="https://cdn.hashnode.com/uploads/covers/67e55054a0be57d730442ec0/ef6ca391-3744-4915-9118-4996124adc85.png" alt="Blank window with title changed to 'Calculator'" style="display:block;margin:0 auto" width="302" height="281" loading="lazy">

<p>Now you should be able to see that the title of the window changed successfully.</p>
<h2 id="heading-how-to-create-frames-in-the-window">How to Create Frames in the Window</h2>
<p>After setting up the window, now we have to place the buttons on it. For placing the buttons, we need to create a container in which we'll put them.</p>
<p>The container could be the main window, but we'll avoid that for this project. This is because we want to place some buttons to the side of and below others to create our keyboard. To make it easier, we'll create Frame containers.</p>
<p>A Frame container represents a vertical column of the window. The initial dimension of the frame is 0 x 0. The frame resizes accordingly when we place a widget in it.</p>
<p>We'll create four frames in our window. The first frame will contain the buttons 1, 4, 7, and AC. The second frame will contain the buttons 2, 5, 8, and 0, the third frame will contain the buttons 3, 6, 9, and =, and the last frame will contain the buttons +, -, x, and / (just like in the UI shown above).</p>
<p>We can create frames in Tkinter using <code>tk.Frame()</code>. We'll pass the parent container for the Frame – that is, the main window in its argument. The following code should make it clear:</p>
<pre><code class="language-python">import tkinter as tk

# screen initialization
root = tk.Tk()

# Naming the window
root.title("Calculator")

# Creating Frames
frame1 = tk.Frame(root)
frame1.pack(side='left', anchor='n')
frame2 = tk.Frame(root)
frame2.pack(side='left', anchor='n')
frame3 = tk.Frame(root)
frame3.pack(side='left', anchor='n')
frame4 = tk.Frame(root)
frame4.pack(side='left', anchor='n')

# This keeps the window active
root.mainloop()
</code></pre>
<p>The <code>pack()</code> function embeds the Frame geometrically on the window. The <code>side='left'</code> parameter embeds the Frames to the extreme left of the screen. By default, this is set to the center. <code>anchor='n'</code> tells us that the widgets should be placed starting from the very top of the frame. By default, the widgets start adding from the center of the Frame. The 'n' in the <code>anchor='n'</code> stands for 'North'.</p>
<p>An important thing to note is that, since we defined <code>frame1</code> early in the program, it will occupy the extreme left portion of the window. But even though <code>frame2</code> is also set to occupy extreme left, the two frames <code>frame1</code> and <code>frame2</code> won't overlap. Instead <code>frame2</code> will take a position so that it goes as far left as it can go on the window without overlapping <code>frame1</code>. So frames <code>frame1</code>, <code>frame2</code>, <code>frame3</code> and <code>frame4</code> are side by side on the left side of the window.</p>
<h2 id="heading-how-to-add-buttons-to-the-window">How to Add Buttons to the Window</h2>
<p>We can create a button widget in Tkinter by using the <code>tk.Button()</code> function. The <code>tk.Button()</code> function consists of various parameters:</p>
<ul>
<li><p><strong>master:</strong> This allows us to provide the parent container in which we have to place our button. This expects a container object.</p>
</li>
<li><p><strong>text:</strong> In this parameter, we have to pass the text which we want to display on our button. This expects a string.</p>
</li>
<li><p><strong>font:</strong> This expects a tuple with the first element providing the name of the font and the next element providing the font size.</p>
</li>
<li><p><strong>image:</strong> This allows us to put an image over our button.</p>
</li>
<li><p><strong>bg:</strong> This allows us to set the background colour for our button.</p>
</li>
<li><p><strong>fg:</strong> This allows us to set the foreground colour for our button.</p>
</li>
<li><p><strong>activebackground:</strong> When the button is clicked, the colour passed in this parameter becomes visible.</p>
</li>
<li><p><strong>command:</strong> This allows us to link a command to the button.</p>
</li>
</ul>
<p>Now that we know the basics of creating a button, lets actually create the keyboard of our calculator.</p>
<p>To create the keyboard, we have to put quite a few buttons on the window. To make our work easier, we'll define a function to create our buttons, just with different text. Let's look at the code below:</p>
<pre><code class="language-python">import tkinter as tk

# screen initialization
root = tk.Tk()

# Naming the window
root.title("Calculator")

frame1 = tk.Frame(root)
frame1.pack(side='left', anchor='n')
frame2 = tk.Frame(root)
frame2.pack(side='left', anchor='n')
frame3 = tk.Frame(root)
frame3.pack(side='left', anchor='n')
frame4 = tk.Frame(root)
frame4.pack(side='left', anchor='n')

pixel = tk.PhotoImage(width=55, height=55)

def buttons(text, frame):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg="#333300", fg="white", compound="center")
    return button


def buttons_ops(text, frame, bg, fg):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg=bg, fg=fg, activebackground="black",
                        compound="center")
    return button

btn1 = buttons('1',frame1).pack()
btn4 = buttons('4', frame1).pack()
btn7 = buttons('7', frame1).pack()

btn2 = buttons('2', frame2).pack()
btn5 = buttons('5', frame2).pack()
btn8 = buttons('8', frame2).pack()
btn0 = buttons_ops('0', frame2, '#333300', 'white').pack()

plus = buttons_ops('+', frame4, 'black', 'white').pack()
minus= buttons_ops('-', frame4,  'black', 'white').pack()
mul = buttons_ops('x', frame4, 'black', 'white').pack()
div = buttons_ops('/', frame4, 'black', 'white').pack()

btn3 = buttons('3', frame3).pack()
btn6 = buttons('6', frame3).pack()
btn9 = buttons('9', frame3).pack()

# This keeps the window active
root.mainloop()
</code></pre>
<p>Now let's break it down:</p>
<p>First, we created an Tkinter image object via <code>tk.PhotoImage()</code>. This is a transparent image. The purpose behind creating this image is to set a perfect width and height of the button pixel-wise. The <code>compound='center'</code> ensures that the button text is aligned at the center of the transparent image.</p>
<p>You can change the size of the button by changing the <code>width</code> and <code>height</code> parameters of the <code>pixel</code> object.</p>
<p>Secondly, we created a function which takes the 'text' and the 'container frame' as the argument. Inside the function, we created a button object and returned it. For the numerical buttons, we've created the function <code>buttons</code> whereas for operator buttons, we've created the function <code>buttons_ops</code>. This was done only to ensure different style of buttons (in terms of background and foreground, and so on).</p>
<p>You can change the colours of the buttons by making changes in the <code>bg</code> and <code>fg</code> parameters of the <code>tk.Button()</code> function.</p>
<p>Then we created all the buttons with these two functions. The <code>pack()</code> function puts the buttons in their respective places. Remember that we haven't created the <code>=</code> and <code>AC</code> buttons.</p>
<p>When we execute the program, the following window will pop up:</p>
<img src="https://cdn.hashnode.com/uploads/covers/67e55054a0be57d730442ec0/012c6883-d79b-44fa-8171-0c6cfc837b4e.png" alt="Window with embedded buttons " style="display:block;margin:0 auto" width="269" height="289" loading="lazy">

<p>You can try clicking the buttons to make sure that everything is working great up to this point.</p>
<h2 id="heading-how-to-add-the-output-screen-of-the-calculator">How to Add the Output Screen of the Calculator</h2>
<p>For the output screen of the calculator, we'll be using the <code>Entry</code> object in Tkinter. The <code>Entry</code> object will be the best match in this case because we want a single line screen to showcase the user input. We could also use a <code>Text</code> object, but it provides a multiline area. So here, we'll just be using the <code>Entry</code> object.</p>
<p>Also, since we want the output screen to be on the top of the keyboard, we need to define and embed this object before embedding the frames.</p>
<p>The <code>Entry</code> object is created using the <code>tk.Entry()</code> function. This has similar parameters to the <code>tk.Button()</code> function. The following code creates an entry box:</p>
<pre><code class="language-python">import tkinter as tk

# screen initialization
root = tk.Tk()

# Naming the window
root.title("Calculator")

# creating the output screen
entry = tk.Entry(root, width=9, font=('Arial', 38, 'bold'), state='readonly')
entry.pack(pady=(30, 10))


frame1 = tk.Frame(root)
frame1.pack(side='left', anchor='n')
frame2 = tk.Frame(root)
frame2.pack(side='left', anchor='n')
frame3 = tk.Frame(root)
frame3.pack(side='left', anchor='n')
frame4 = tk.Frame(root)
frame4.pack(side='left', anchor='n')

pixel = tk.PhotoImage(width=55, height=55)

def buttons(text, frame):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg="#333300", fg="white", compound="center")
    return button


def buttons_ops(text, frame, bg, fg):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg=bg, fg=fg, activebackground="black",
                        compound="center")
    return button

btn1 = buttons('1',frame1).pack()
btn4 = buttons('4', frame1).pack()
btn7 = buttons('7', frame1).pack()

btn2 = buttons('2', frame2).pack()
btn5 = buttons('5', frame2).pack()
btn8 = buttons('8', frame2).pack()
btn0 = buttons_ops('0', frame2, '#333300', 'white').pack()

plus = buttons_ops('+', frame4, 'black', 'white').pack()
minus= buttons_ops('-', frame4,  'black', 'white').pack()
mul = buttons_ops('x', frame4, 'black', 'white').pack()
div = buttons_ops('/', frame4, 'black', 'white').pack()

btn3 = buttons('3', frame3).pack()
btn6 = buttons('6', frame3).pack()
btn9 = buttons('9', frame3).pack()

# This keeps the window active
root.mainloop()
</code></pre>
<p>In the code above, we put the parent container of the <code>entry</code> object as the main window <code>root</code>. I set the <code>width</code> parameter to 9 as it fit well with the dimensions of the window and the keyboard. You can try it out with different values for width and set a perfectly sized output screen.</p>
<p>You may have noticed that we didn't use the <code>pack()</code> on the same line as object definition. This is because using <code>pack()</code> on the same line as object definition is a bad practice as it limits certain functionality.</p>
<p>So, why did we use the <code>pack()</code> function on the same line while creating buttons? This is because we didn't work heavily with the buttons in this project, so we attempted to reduce the lines of code.</p>
<p>In the <code>tk.Entry()</code> function, we set <code>state='readonly'</code>. This prohibits any direct text input into the the output screen. That means, we can only use the buttons to show the characters on the output screen. By default, this is set to <code>state='normal'</code>, which allows direct input from the keyboard into the entry box.</p>
<p>The <code>pady</code> parameter inside the <code>pack()</code> function leaves the given amount of pixels above and below the object. To perform such an operation, let's say to pad 10 pixels on both sides of the object, we can write <code>pady=10</code> .</p>
<p>Here, we didn't want the same amount of padding above and below the object. So we used a tuple with first element representing the pixels to pad above the output screen, and the second element representing the pixels to pad below the output screen.</p>
<p>Up until now, our GUI looks as shown below:</p>
<img src="https://cdn.hashnode.com/uploads/covers/67e55054a0be57d730442ec0/dc15d02d-2243-4751-b825-53d5b4061daf.png" alt="Window with embedded output screen" style="display:block;margin:0 auto" width="262" height="389" loading="lazy">

<p>We can now see that the output screen is set perfectly.</p>
<h2 id="heading-how-to-make-the-numbers-visible-on-the-output-screen">How to Make the Numbers Visible on the Output Screen</h2>
<p>Next step is to make characters visible on the output screen. Every button that we click should render on the output screen. For this, we have to link commands to each button. Let's first look at the code and then see how it works:</p>
<pre><code class="language-python">import tkinter as tk

# screen initialization
root = tk.Tk()

# Naming the window
root.title("Calculator")

entry = tk.Entry(root, width=9, font=('Arial', 38, 'bold'),state='readonly')
entry.pack(pady=(30, 10))


frame1 = tk.Frame(root)
frame1.pack(side='left', anchor='n')
frame2 = tk.Frame(root)
frame2.pack(side='left', anchor='n')
frame3 = tk.Frame(root)
frame3.pack(side='left', anchor='n')
frame4 = tk.Frame(root)
frame4.pack(side='left', anchor='n')

pixel = tk.PhotoImage(width=55, height=55)

def command(text):
    entry.config(state='normal')
    entry.insert(tk.END, text) 
    entry.config(state='readonly')  


def buttons(text, frame):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg="#333300", fg="white", compound="center",
                       command=lambda :command(text))
    return button


def buttons_ops(text, frame, bg, fg):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg=bg, fg=fg, activebackground="black",
                        compound="center", command=lambda:command(text))
    return button

btn1 = buttons('1',frame1).pack()
btn4 = buttons('4', frame1).pack()
btn7 = buttons('7', frame1).pack()

btn2 = buttons('2', frame2).pack()
btn5 = buttons('5', frame2).pack()
btn8 = buttons('8', frame2).pack()
btn0 = buttons_ops('0', frame2, '#333300', 'white').pack()

plus = buttons_ops('+', frame4, 'black', 'white').pack()
minus= buttons_ops('-', frame4,  'black', 'white').pack()
mul = buttons_ops('x', frame4, 'black', 'white').pack()
div = buttons_ops('/', frame4, 'black', 'white').pack()

btn3 = buttons('3', frame3).pack()
btn6 = buttons('6', frame3).pack()
btn9 = buttons('9', frame3).pack()

# This keeps the window active
root.mainloop()
</code></pre>
<p>In the code above, we defined a new function called <code>command()</code>. This function takes one argument <code>text</code>. Inside the function, we changed the <code>state</code> of the <code>entry</code> object to <code>normal</code> via <code>config</code>. By doing this, we can now make changes in the text of the <code>entry</code> object.</p>
<p>Then we used the <code>insert()</code> function for the <code>entry</code> object. The <code>insert()</code> function appends the <code>text</code> argument to the existing set of characters.</p>
<p>The first argument of the <code>insert()</code> function takes the index where the text will be inserted. <code>tk.END</code> represents the last character of the text in the object. The second argument of the <code>insert()</code> function takes the text that is to be inserted.</p>
<p>Finally, we change the <code>state</code> of the object again to <code>readonly</code> to prohibit any outside input other than our defined calculator keyboard.</p>
<p>Now let's look at the <code>buttons</code> and the <code>buttons_ops</code> functions. You may have noticed that we've added the <code>command</code> parameter to the <code>tk.Button()</code> function. The <code>lambda</code> tells the program to perform the command only when the button is clicked.</p>
<p>Collectively, <code>command=lambda:command(text)</code> means that, on clicking the buttons which we have defined up until now, it executes the <code>command()</code> function and shows the pressed button character on the output screen.</p>
<p>Now try clicking some buttons on your window. They should appear on the output screen as shown below:</p>
<img src="https://cdn.hashnode.com/uploads/covers/67e55054a0be57d730442ec0/e8cc0cd5-dc0c-4f01-9b21-7dec6874d00f.png" alt="Image of the calculator showing input on the calculator screen" style="display:block;margin:0 auto" width="262" height="395" loading="lazy">

<h2 id="heading-how-to-add-a-scrollbar-to-the-output-screen">How to Add a Scrollbar to the Output Screen</h2>
<p>Now, you might have encountered a problem: when you input a large number of characters, you were able to see only the first few characters. The rest were invisible.</p>
<p>To tackle this, we'll add a scrollbar to the output screen.</p>
<p>First, we'll create a scrollbar object via <code>tk.Scrollbar()</code> before the <code>entry</code> object. The following code shows how:</p>
<pre><code class="language-python">import tkinter as tk

# screen initialization
root = tk.Tk()

# Naming the window
root.title("Calculator")

scrollbar = tk.Scrollbar(root, orient='horizontal')

entry = tk.Entry(root, width=9, font=('Arial', 38, 'bold'), state='readonly', xscrollcommand=scrollbar.set)
entry.pack(pady=(30, 10))

scrollbar.config(command=entry.xview)
scrollbar.pack()

frame1 = tk.Frame(root)
frame1.pack(side='left', anchor='n')
frame2 = tk.Frame(root)
frame2.pack(side='left', anchor='n')
frame3 = tk.Frame(root)
frame3.pack(side='left', anchor='n')
frame4 = tk.Frame(root)
frame4.pack(side='left', anchor='n')

pixel = tk.PhotoImage(width=55, height=55)

def command(text):
    entry.config(state='normal')
    entry.insert(tk.END, text)
    entry.config(state='readonly')


def buttons(text, frame):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg="#333300", fg="white", compound="center",
                       command=lambda :command(text))
    return button


def buttons_ops(text, frame, bg, fg):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg=bg, fg=fg, activebackground="black",
                        compound="center", command=lambda:command(text))
    return button

btn1 = buttons('1',frame1).pack()
btn4 = buttons('4', frame1).pack()
btn7 = buttons('7', frame1).pack()

btn2 = buttons('2', frame2).pack()
btn5 = buttons('5', frame2).pack()
btn8 = buttons('8', frame2).pack()
btn0 = buttons_ops('0', frame2, '#333300', 'white').pack()

plus = buttons_ops('+', frame4, 'black', 'white').pack()
minus= buttons_ops('-', frame4,  'black', 'white').pack()
mul = buttons_ops('x', frame4, 'black', 'white').pack()
div = buttons_ops('/', frame4, 'black', 'white').pack()

btn3 = buttons('3', frame3).pack()
btn6 = buttons('6', frame3).pack()
btn9 = buttons('9', frame3).pack()

# This keeps the window active
root.mainloop()
</code></pre>
<p>The <code>orient</code> parameter in the <code>tk.Scrollbar()</code> object determines the nature of the scrollbar. Here, we've aligned it with the X-axis. We also added a parameter in the original <code>entry</code> object. The <code>xscrollcommand</code> sets the scrollbar to the output screen.</p>
<p>Then we connected the scrollbar to the entry object by setting <code>command=entry.xview</code> and embedded the scrollbar in the output screen.</p>
<p>The following image shows the scrollbar. You can use the arrow signs to navigate forward or backward through the text:</p>
<img src="https://cdn.hashnode.com/uploads/covers/67e55054a0be57d730442ec0/29d0fd37-a94f-4bad-af24-6627055fd4b3.png" alt="Image of calculator with the scrollbar" style="display:block;margin:0 auto" width="283" height="429" loading="lazy">

<h2 id="heading-how-to-add-the-equal-to-button">How to Add the Equal To Button</h2>
<p>We haven't yet made the <code>equal to</code> button – so let's do that now. To start, we'll define a function called <code>cmd_equal()</code>. In this function, we'll first change the <code>state</code> of the <code>entry</code> to <code>normal</code>. Then we'll extract the text in the output screen using the <code>entry.get()</code> function and replace 'x' by '*'. We do this because multiplication is represented by '*' and not 'x'.</p>
<p>Then we'll add a <code>try-except</code> block. We'll try to evaluate the mathematical expression that we extracted using Python's built-in <code>eval()</code> function. If that's invalid, instead of throwing an error, we'll output 'Invalid' onto our screen.</p>
<pre><code class="language-python">import tkinter as tk

# screen initialization
root = tk.Tk()

# Naming the window
root.title("Calculator")

scrollbar = tk.Scrollbar(root, orient='horizontal')

entry = tk.Entry(root, width=9, font=('Arial', 38, 'bold'), state='readonly', xscrollcommand=scrollbar.set)
entry.pack(pady=(30, 10))

scrollbar.config(command=entry.xview)
scrollbar.pack()

frame1 = tk.Frame(root)
frame1.pack(side='left', anchor='n')
frame2 = tk.Frame(root)
frame2.pack(side='left', anchor='n')
frame3 = tk.Frame(root)
frame3.pack(side='left', anchor='n')
frame4 = tk.Frame(root)
frame4.pack(side='left', anchor='n')

pixel = tk.PhotoImage(width=55, height=55)

def command(text):
    entry.config(state='normal')
    entry.insert(tk.END, text)
    entry.config(state='readonly')

def cmd_equal():
    entry.config(state='normal')
    txt = entry.get().replace('x', '*')

    try:
        result = eval(txt)

    except:
        result = 'INVALID'
    entry.delete(0, tk.END)
    entry.insert(tk.END, result)
    entry.config(state='readonly')   


def buttons(text, frame):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg="#333300", fg="white", compound="center",
                       command=lambda :command(text))
    return button


def buttons_ops(text, frame, bg, fg):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg=bg, fg=fg, activebackground="black",
                        compound="center", command=lambda:command(text))
    return button

btn1 = buttons('1',frame1).pack()
btn4 = buttons('4', frame1).pack()
btn7 = buttons('7', frame1).pack()

btn2 = buttons('2', frame2).pack()
btn5 = buttons('5', frame2).pack()
btn8 = buttons('8', frame2).pack()
btn0 = buttons_ops('0', frame2, '#333300', 'white').pack()

plus = buttons_ops('+', frame4, 'black', 'white').pack()
minus= buttons_ops('-', frame4,  'black', 'white').pack()
mul = buttons_ops('x', frame4, 'black', 'white').pack()
div = buttons_ops('/', frame4, 'black', 'white').pack()

btn3 = buttons('3', frame3).pack()
btn6 = buttons('6', frame3).pack()
btn9 = buttons('9', frame3).pack()
equal= tk.Button(frame3, text='=', font=('Arial', 20), image=pixel, bg='white', fg='black', activebackground="black",
                        compound="center", command=lambda: cmd_equal()).pack()

# This keeps the window active
root.mainloop()
</code></pre>
<p>Here, we've also used <code>entry.delete()</code>. This function will delete all the text on the output screen from the first argument's index (that is from the 0th index) to the last argument's index, that is to the end of the text (represented by <code>tk.END</code>).</p>
<p>Then we inserted our result onto the output screen using <code>entry.insert()</code>. An important thing to note is that we've embedded the <code>equal to</code> button below the definition of <code>btn9</code> in the same frame. This puts our <code>equal to</code> button in just the right place.</p>
<p>The following images show the initial and final screens, respectively.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67e55054a0be57d730442ec0/8051ce51-5139-4668-97e2-b5c742c687a1.png" alt="Calculator window showing mathematical expression " style="display:block;margin:0 auto" width="270" height="407" loading="lazy">

<p>On clicking the equal to button:</p>
<img src="https://cdn.hashnode.com/uploads/covers/67e55054a0be57d730442ec0/1ddc6b4c-3e51-4237-b9f6-90986bff1963.png" alt="Calculator window showing evaluated mathematical expression" style="display:block;margin:0 auto" width="267" height="407" loading="lazy">

<h2 id="heading-how-to-add-the-ac-button">How to Add the AC Button</h2>
<p>Now finally, we'll define our last function: <code>cmd_ac()</code>. This function will delete everything on the output screen. We'll do this by first changing the <code>state</code> to <code>normal</code>, then using <code>entry.delete()</code>, and lastly changing the <code>state</code> back to <code>readonly</code>. Then we'll put this function in the <code>command()</code> parameter of the <code>ac</code> button.</p>
<p>To keep the UI from dismantling when we expand the window, we'll use the <code>resizable()</code> function. This functions takes two arguments: one corresponds to the permission to expand the width and the other to the height. To prohibit expansion of the window, we'll set both the parameters to <code>False</code>.</p>
<p>So the final code will be:</p>
<pre><code class="language-python">import tkinter as tk

# screen initialization
root = tk.Tk()

# Naming the window
root.title("Calculator")

scrollbar = tk.Scrollbar(root, orient='horizontal')

entry = tk.Entry(root, width=9, font=('Arial', 38, 'bold'), state='readonly', xscrollcommand=scrollbar.set)
entry.pack(pady=(30, 10))

scrollbar.config(command=entry.xview)
scrollbar.pack()

frame1 = tk.Frame(root)
frame1.pack(side='left', anchor='n')
frame2 = tk.Frame(root)
frame2.pack(side='left', anchor='n')
frame3 = tk.Frame(root)
frame3.pack(side='left', anchor='n')
frame4 = tk.Frame(root)
frame4.pack(side='left', anchor='n')

pixel = tk.PhotoImage(width=55, height=55)

def command(text):
    entry.config(state='normal')
    entry.insert(tk.END, text)
    entry.config(state='readonly')

def cmd_ac():
    entry.config(state='normal')
    entry.delete(0, tk.END)
    entry.config(state='readonly')

def cmd_equal():
    entry.config(state='normal')
    txt = entry.get().replace('x', '*')

    try:
        result = eval(txt)

    except:
        result = 'INVALID'
    entry.delete(0, tk.END)
    entry.insert(tk.END, result)
    entry.config(state='readonly')


def buttons(text, frame):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg="#333300", fg="white", compound="center",
                       command=lambda :command(text))
    return button


def buttons_ops(text, frame, bg, fg):
    button = tk.Button(frame, text=text, font=('Arial', 20), image=pixel, bg=bg, fg=fg, activebackground="black",
                        compound="center", command=lambda:command(text))
    return button

btn1 = buttons('1',frame1).pack()
btn4 = buttons('4', frame1).pack()
btn7 = buttons('7', frame1).pack()
ac = tk.Button(frame1, text="AC", font=('Arial', 20), image=pixel, bg="#666699", fg="white", compound="center",
                        command=lambda: cmd_ac()).pack()

btn2 = buttons('2', frame2).pack()
btn5 = buttons('5', frame2).pack()
btn8 = buttons('8', frame2).pack()
btn0 = buttons_ops('0', frame2, '#333300', 'white').pack()

plus = buttons_ops('+', frame4, 'black', 'white').pack()
minus= buttons_ops('-', frame4,  'black', 'white').pack()
mul = buttons_ops('x', frame4, 'black', 'white').pack()
div = buttons_ops('/', frame4, 'black', 'white').pack()

btn3 = buttons('3', frame3).pack()
btn6 = buttons('6', frame3).pack()
btn9 = buttons('9', frame3).pack()
equal= tk.Button(frame3, text='=', font=('Arial', 20), image=pixel, bg='white', fg='black', activebackground="black",
                        compound="center", command=lambda: cmd_equal()).pack()


root.resizable(0,0) 
# This keeps the window active
root.mainloop()
</code></pre>
<p>When we hit run, this should display our final project.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>So now you know how to build a simple arithmetic calculator. To strengthen and build upon the concepts that you learned here, you can try to add some more functionality to this calculator. Here are some ideas for you to practice the things learnt here:</p>
<ul>
<li><p>Adding a decimal point button to the calculator to allow users work with fractional numbers.</p>
</li>
<li><p>Adding percentage button to the calculator to allow users calculate percentages.</p>
</li>
<li><p>Adding a delete button to the calculator which, instead of clearing entire screen, deletes one character at a time.</p>
</li>
<li><p>Making the calculator 'computer keyboard interactive', that is, allowing input directly from the computer keyboard. (Hint for this task: changing the <code>state</code> of the <code>entry</code> object to <code>normal</code>, and adding conditions for 'invalid' expressions).</p>
</li>
</ul>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
