Holistic Lesson Plan: Interactive
Python Calculator with Tkinter
Tkinter
"Who invented the first calculator?
What do you think it looked like?"
Let’s make a timeline of evolution of calculators
based on your guesses
1. Abacus
2. Typewriter
3. Very big
4. Heavy
5. Not portable
6. Few functions and very heavy and big
7. Slow
"Can you imagine doing your math homework
without a calculator? How would it be different?"
"Why is it important that calculators are accurate?
What could happen if a calculator made mistakes?"
What if these calculators were not accurate and had
errors?
Enlist consequences of faulty calculators or calculations machines in different
sectors of society and business:
Imagine you are designing a calculator for a spaceship.
What extra checks would you include to make sure it’s
always accurate?
Create the Window:
import tkinter as tk
window = tk.Tk()
window.title("My First Interactive Calculator")
window.configure(bg="#2e2e2e") #
Background color
Create Buttons:
# Function to add numbers or operators to the
display when a button is pressed
def button_click(number):
current = display.get()
display.delete(0, tk.END)
display.insert(0, current + str(number))
Create a clear button:
# Function to clear everything on the display
def button_clear():
display.delete(0, tk.END) # Use tk.END to
delete everything
Create equal button with Error exception
def button_equal():
try:
result = eval(display.get()) # Evaluate the math expression
display.delete(0, tk.END) # Use tk.END to clear the display
display.insert(0, str(result)) # Show the result
except:
display.delete(0, tk.END)
display.insert(0, "Error") # Show error if there is a problem with the input
Syntax to add a button
# General Format to Create a Button and Add to the Window
button_name = tk.Button(window, text="Button Text", command=lambda:
function_name(argument))
button_name.pack(side=tk.SIDE, padx=padding_value, pady=padding_value)
#Example: Create button that displays and inputs value 1
button1 = tk.Button(window, text="1", command=lambda: button_click(1))
button1.pack(side=tk.LEFT, padx=5, pady=5)
button_add = tk.Button(window, text="+", command=lambda: button_click("+"))
button_add.pack(side=tk.LEFT, padx=5, pady=5)
Now add more buttons to you calculator using
this syntax and calling the required function