SoFunction
Updated on 2025-05-04

Create a full-featured Windows-style calculator program using Python

Python implements Windows system calculator program (including advanced functions)

Below I will introduce how to create a full-featured Windows-style calculator program using Python, including basic operations and advanced math functions.

1. Implement the basic calculator using Tkinter

import tkinter as tk
from tkinter import ttk
import math
 
class Calculator:
    def __init__(self, root):
         = root
        ("Advanced Calculator")
        ("400x550")
        (False, False)
        
        # Current input and results        self.current_input = ""
        self.previous_input = ""
         = None
        self.reset_input = False
        
        # Create an interface        self.create_widgets()
    
    def create_widgets(self):
        # Show box        self.display_frame = ()
        self.display_frame.pack(fill=, padx=10, pady=10)
        
        self.expression_var = ()
        self.expression_label = (
            self.display_frame, 
            textvariable=self.expression_var,
            font=("Arial", 18),
            anchor=
        )
        self.expression_label.pack(fill=, expand=True)
        
        self.result_var = ()
        self.result_label = (
            self.display_frame, 
            textvariable=self.result_var,
            font=("Arial", 28, "bold"),
            anchor=,
            foreground="blue"
        )
        self.result_label.pack(fill=, expand=True)
        
        # Button frame        self.buttons_frame = ()
        self.buttons_frame.pack(fill=, expand=True)
        
        # Button layout        buttons = [
            ("C", 0, 0, "#FF9500", self.clear_all),
            ("⌫", 0, 1, "#FF9500", self.delete_last),
            ("÷", 0, 2, "#FF9500", lambda: self.add_operation("/")),
            ("×", 0, 3, "#FF9500", lambda: self.add_operation("*")),
            
            ("7", 1, 0, "#333333", lambda: self.add_number("7")),
            ("8", 1, 1, "#333333", lambda: self.add_number("8")),
            ("9", 1, 2, "#333333", lambda: self.add_number("9")),
            ("-", 1, 3, "#FF9500", lambda: self.add_operation("-")),
            
            ("4", 2, 0, "#333333", lambda: self.add_number("4")),
            ("5", 2, 1, "#333333", lambda: self.add_number("5")),
            ("6", 2, 2, "#333333", lambda: self.add_number("6")),
            ("+", 2, 3, "#FF9500", lambda: self.add_operation("+")),
            
            ("1", 3, 0, "#333333", lambda: self.add_number("1")),
            ("2", 3, 1, "#333333", lambda: self.add_number("2")),
            ("3", 3, 2, "#333333", lambda: self.add_number("3")),
            ("=", 3, 3, "#4CD964", ),
            
            ("0", 4, 0, "#333333", lambda: self.add_number("0")),
            (".", 4, 1, "#333333", lambda: self.add_number(".")),
            ("(", 4, 2, "#333333", lambda: self.add_number("(")),
            (")", 4, 3, "#333333", lambda: self.add_number(")")),
            
            # Advanced Function Button            ("sin", 5, 0, "#5856D6", lambda: self.add_function("(")),
            ("cos", 5, 1, "#5856D6", lambda: self.add_function("(")),
            ("tan", 5, 2, "#5856D6", lambda: self.add_function("(")),
            ("log", 5, 3, "#5856D6", lambda: self.add_function("math.log10(")),
            
            ("√", 6, 0, "#5856D6", lambda: self.add_function("(")),
            ("x²", 6, 1, "#5856D6", lambda: self.add_operation("**2")),
            ("x³", 6, 2, "#5856D6", lambda: self.add_operation("**3")),
            ("π", 6, 3, "#5856D6", lambda: self.add_number(str())),
            
            ("e", 7, 0, "#5856D6", lambda: self.add_number(str())),
            ("x^y", 7, 1, "#5856D6", lambda: self.add_operation("**")),
            ("(", 7, 2, "#333333", lambda: self.add_number("(")),
            (")", 7, 3, "#333333", lambda: self.add_number(")")),
            
            ("Ans", 8, 0, "#5856D6", lambda: self.add_number(str(self.previous_result))),
            ("1/x", 8, 1, "#5856D6", lambda: self.add_function("1/(" + self.current_input + ")")),
            ("n!", 8, 2, "#5856D6", lambda: self.add_function("(int(" + self.current_input + "))" if self.current_input.isdigit() else "")),
            ("(", 8, 3, "#333333", lambda: self.add_number("(")),
        ]
        
        # Create button        for (text, row, col, color, command) in buttons:
            button = (
                self.buttons_frame,
                text=text,
                command=command
            )
            
            if () or text in [".", "+", "-", "*", "/", "(", ")", "^"]:
                (style="")
            elif text in ["sin", "cos", "tan", "log", "√", "x²", "x³", "Ans", "1/x", "n!"]:
                (style="")
            else:
                (style="")
            
            (row=row, column=col, sticky="nsew", padx=5, pady=5)
            
            # Configure grid weights            self.buttons_frame.grid_rowconfigure(row, weight=1)
            self.buttons_frame.grid_columnconfigure(col, weight=1)
        
        # Set button style        style = ()
        ("TButton", font=("Arial", 14))
        ("TButton",
                 foreground=[('pressed', 'white'), ('active', '#007AFF')],
                 background=[('pressed', '#007AFF'), ('active', '#007AFF')],
                 relief=[('pressed', 'flat'), ('active', 'flat')])
        
        ("", background="#F2F2F7")
        ("", background="#FF9500", foreground="white")
        ("", background="#5856D6", foreground="white")
        
        # Calculate the result variable        self.previous_result = 0
    
    def add_number(self, number):
        if self.reset_input:
            self.current_input = ""
            self.reset_input = False
            
        if number == "." and "." in self.current_input:
            return
            
        self.current_input += number
        self.expression_var.set(self.current_input)
    
    def add_operation(self, operation):
        if self.current_input == "" and self.previous_input == "":
            return
            
        if self.previous_input:
            ()
             = operation
        else:
             = operation
            self.previous_input = self.current_input
            self.current_input = ""
            
        self.expression_var.set(self.previous_input + " " + operation)
    
    def add_function(self, function):
        if self.reset_input:
            self.current_input = ""
            self.reset_input = False
            
        # Check if brackets are required        if not (self.current_input.endswith(")") or self.current_input == ""):
            self.current_input += ")"
            
        self.current_input += function
        if not self.current_input.endswith(")"):
            self.current_input += "("
            
        self.expression_var.set(self.current_input)
    
    def clear_all(self):
        self.current_input = ""
        self.previous_input = ""
         = None
        self.reset_input = False
        self.expression_var.set("")
        self.result_var.set("")
    
    def delete_last(self):
        if self.current_input:
            self.current_input = self.current_input[:-1]
            self.expression_var.set(self.current_input if self.current_input else "")
        elif self.previous_input:
            self.previous_input = self.previous_input[:-1]
            self.expression_var.set(self.previous_input if self.previous_input else "")
    
    def calculate(self):
        try:
            # Replace x with * for calculation            expression = self.current_input.replace("^", "**")
            
            # Handle special functions            if "sin(" in expression:
                expression = ("sin(", "(")
            if "cos(" in expression:
                expression = ("cos(", "(")
            if "tan(" in expression:
                expression = ("tan(", "(")
            if "log(" in expression:
                expression = ("log(", "math.log10(")
            if "√(" in expression:
                expression = ("√(", "(")
                
            result = eval(expression, {"math": math})
            
            self.previous_input = str(result)
            self.current_input = str(result)
            self.expression_var.set(str(result))
            self.result_var.set("=" + str(result))
            self.previous_result = result
            self.reset_input = True
            
        except Exception as e:
            self.expression_var.set("mistake")
            self.result_var.set("")
            self.current_input = ""
            self.previous_input = ""
            self.reset_input = False
    
    @property
    def current_input(self):
        return self._current_input
    
    @current_input.setter
    def current_input(self, value):
        self._current_input = value
 
# Create the main window and run the calculatorif __name__ == "__main__":
    import math
    
    root = ()
    calculator = Calculator(root)
    
    # Add custom styles    style = ()
    style.theme_use('clam')
    
    ()

2. Advanced function implementation

2.1 Scientific computing functions

The above code has implemented the following advanced functions:

  • Trigonometric functions: sin, cos, tan
  • Logarithmic function: log10
  • Square root: √
  • Power operations: x², x³, x^y
  • Constant: π, e
  • Factorial: n!
  • Inverse function: 1/x

2.2 History function (extended)

To add history function, you can modify the code as follows:

class Calculator:
    def __init__(self, root):
        # ...Other initialization codes ...         = []  #Storing computing history        
    def calculate(self):
        try:
            # ... Calculate code ...            
            # Add to history            if self.previous_input and  and self.current_input:
                expression = f"{self.previous_input} {} {self.current_input}"
                ((expression, str(result)))
                if len() > 10:  # Limit the number of history records                    (0)
                    
            # ...Other codes ...            
        except Exception as e:
            # ... Error handling code ...    
    def show_history(self):
        # Create a new window to display history        history_window = ()
        history_window.title("Computation History")
        history_window.geometry("350x400")
        
        history_text = (history_window, font=("Arial", 12))
        history_text.pack(fill=, expand=True, padx=10, pady=10)
        
        for expr, res in :
            history_text.insert(, f"{expr} = {res}\n")
        
        history_text.config(state=)

2.3 Graphic drawing function (extended)

To add function graph drawing functionality, you can use matplotlib:

import  as plt
from .backend_tkagg import FigureCanvasTkAgg
 
class Calculator:
    # ...Other codes ...    
    def plot_function(self):
        function_window = ()
        function_window.title("Function Drawing")
        function_window.geometry("600x500")
        
        # Create an input box        input_frame = (function_window)
        input_frame.pack(fill=, padx=10, pady=10)
        
        (input_frame, text="Input function (usexAs a variable):").pack(side=)
        function_entry = (input_frame, width=30)
        function_entry.pack(side=, padx=5)
        function_entry.insert(0, "(x)")  # Default function        
        # Create a drawing area        fig_frame = (function_window)
        fig_frame.pack(fill=, expand=True, padx=10, pady=10)
        
        fig, ax = (figsize=(6, 5))
        canvas = FigureCanvasTkAgg(fig, master=fig_frame)
        canvas.get_tk_widget().pack(fill=, expand=True)
        
        # Draw buttons        def draw_plot():
            try:
                func_str = function_entry.get()
                x = (-10, 10, 400)
                y = eval(func_str, {"math": math, "x": x, "np": np})
                
                ()
                (x, y)
                ax.set_title(f"y = {func_str}")
                (True)
                ()
            except Exception as e:
                ("mistake", f"Cannot draw function: {str(e)}")
        
        (function_window, text="draw", command=draw_plot).pack(pady=5)

3. Complete functional integration

Integrate the above functionality into a complete calculator program:

import tkinter as tk
from tkinter import ttk, messagebox
import math
import numpy as np
 
class AdvancedCalculator:
    def __init__(self, root):
         = root
        ("Advanced Scientific Calculator")
        ("500x650")
        (False, False)
        
        self.current_input = ""
        self.previous_input = ""
         = None
        self.reset_input = False
         = []
        
        self.create_widgets()
    
    def create_widgets(self):
        # Show box        self.display_frame = ()
        self.display_frame.pack(fill=, padx=10, pady=10)
        
        self.expression_var = ()
        self.expression_label = (
            self.display_frame, 
            textvariable=self.expression_var,
            font=("Arial", 14),
            anchor=
        )
        self.expression_label.pack(fill=, expand=True)
        
        self.result_var = ()
        self.result_label = (
            self.display_frame, 
            textvariable=self.result_var,
            font=("Arial", 24, "bold"),
            anchor=,
            foreground="blue"
        )
        self.result_label.pack(fill=, expand=True)
        
        # Button frame        self.buttons_frame = ()
        self.buttons_frame.pack(fill=, expand=True)
        
        # Button layout        buttons = [
            # Line 1            ("C", 0, 0, "#FF9500", self.clear_all),
            ("⌫", 0, 1, "#FF9500", self.delete_last),
            ("÷", 0, 2, "#FF9500", lambda: self.add_operation("/")),
            ("×", 0, 3, "#FF9500", lambda: self.add_operation("*")),
            
            # Line 2            ("7", 1, 0, "#333333", lambda: self.add_number("7")),
            ("8", 1, 1, "#333333", lambda: self.add_number("8")),
            ("9", 1, 2, "#333333", lambda: self.add_number("9")),
            ("-", 1, 3, "#FF9500", lambda: self.add_operation("-")),
            
            # Line 3            ("4", 2, 0, "#333333", lambda: self.add_number("4")),
            ("5", 2, 1, "#333333", lambda: self.add_number("5")),
            ("6", 2, 2, "#333333", lambda: self.add_number("6")),
            ("+", 2, 3, "#FF9500", lambda: self.add_operation("+")),
            
            # Line 4            ("1", 3, 0, "#333333", lambda: self.add_number("1")),
            ("2", 3, 1, "#333333", lambda: self.add_number("2")),
            ("3", 3, 2, "#333333", lambda: self.add_number("3")),
            ("=", 3, 3, "#4CD964", ),
            
            # Line 5            ("0", 4, 0, "#333333", lambda: self.add_number("0")),
            (".", 4, 1, "#333333", lambda: self.add_number(".")),
            ("(", 4, 2, "#333333", lambda: self.add_number("(")),
            (")", 4, 3, "#333333", lambda: self.add_number(")")),
            
            # Line 6 - Advanced Features            ("sin", 5, 0, "#5856D6", lambda: self.add_function("(")),
            ("cos", 5, 1, "#5856D6", lambda: self.add_function("(")),
            ("tan", 5, 2, "#5856D6", lambda: self.add_function("(")),
            ("log", 5, 3, "#5856D6", lambda: self.add_function("math.log10(")),
            
            # Line 7            ("√", 6, 0, "#5856D6", lambda: self.add_function("(")),
            ("x²", 6, 1, "#5856D6", lambda: self.add_operation("**2")),
            ("x³", 6, 2, "#5856D6", lambda: self.add_operation("**3")),
            ("π", 6, 3, "#5856D6", lambda: self.add_number(str())),
            
            # Line 8            ("e", 7, 0, "#5856D6", lambda: self.add_number(str())),
            ("x^y", 7, 1, "#5856D6", lambda: self.add_operation("**")),
            ("(", 7, 2, "#333333", lambda: self.add_number("(")),
            (")", 7, 3, "#333333", lambda: self.add_number(")")),
            
            # Line 9            ("Ans", 8, 0, "#5856D6", lambda: self.add_number(str(self.previous_result))),
            ("1/x", 8, 1, "#5856D6", lambda: self.add_function("1/(" + self.current_input + ")")),
            ("n!", 8, 2, "#5856D6", lambda: self.add_function("(int(" + self.current_input + "))" if self.current_input.isdigit() else "")),
            ("Hist", 8, 3, "#5856D6", self.show_history),
        ]
        
        # Create button        for (text, row, col, color, command) in buttons:
            button = (
                self.buttons_frame,
                text=text,
                command=command
            )
            
            if () or text in [".", "+", "-", "*", "/", "(", ")", "^"]:
                (style="")
            elif text in ["sin", "cos", "tan", "log", "√", "x²", "x³", "Ans", "1/x", "n!"]:
                (style="")
            elif text in ["Hist"]:
                (style="")
            else:
                (style="")
            
            (row=row, column=col, sticky="nsew", padx=5, pady=5)
            
            # Configure grid weights            self.buttons_frame.grid_rowconfigure(row, weight=1)
            self.buttons_frame.grid_columnconfigure(col, weight=1)
        
        # Set button style        style = ()
        ("TButton", font=("Arial", 14))
        
        ("TButton",
                 foreground=[('pressed', 'white'), ('active', '#007AFF')],
                 background=[('pressed', '#007AFF'), ('active', '#007AFF')],
                 relief=[('pressed', 'flat'), ('active', 'flat')])
        
        ("", background="#F2F2F7")
        ("", background="#FF9500", foreground="white")
        ("", background="#5856D6", foreground="white")
        ("", background="#8E8E93", foreground="white")
        
        # Calculate the result variable        self.previous_result = 0
    
    def add_number(self, number):
        if self.reset_input:
            self.current_input = ""
            self.reset_input = False
            
        if number == "." and "." in self.current_input:
            return
            
        self.current_input += number
        self.expression_var.set(self.current_input)
    
    def add_operation(self, operation):
        if self.current_input == "" and self.previous_input == "":
            return
            
        if self.previous_input:
            ()
             = operation
        else:
             = operation
            self.previous_input = self.current_input
            self.current_input = ""
            
        self.expression_var.set(self.previous_input + " " + operation)
    
    def add_function(self, function):
        if self.reset_input:
            self.current_input = ""
            self.reset_input = False
            
        # Check if brackets are required        if not (self.current_input.endswith(")") or self.current_input == ""):
            self.current_input += ")"
            
        self.current_input += function
        if not self.current_input.endswith(")"):
            self.current_input += "("
            
        self.expression_var.set(self.current_input)
    
    def clear_all(self):
        self.current_input = ""
        self.previous_input = ""
         = None
        self.reset_input = False
        self.expression_var.set("")
        self.result_var.set("")
    
    def delete_last(self):
        if self.current_input:
            self.current_input = self.current_input[:-1]
            self.expression_var.set(self.current_input if self.current_input else "")
        elif self.previous_input:
            self.previous_input = self.previous_input[:-1]
            self.expression_var.set(self.previous_input if self.previous_input else "")
    
    def calculate(self):
        try:
            # Replace x with * for calculation            expression = self.current_input.replace("^", "**")
            
            # Handle special functions            if "sin(" in expression:
                expression = ("sin(", "(")
            if "cos(" in expression:
                expression = ("cos(", "(")
            if "tan(" in expression:
                expression = ("tan(", "(")
            if "log(" in expression:
                expression = ("log(", "math.log10(")
            if "√(" in expression:
                expression = ("√(", "(")
                
            result = eval(expression, {"math": math})
            
            self.previous_input = str(result)
            self.current_input = str(result)
            self.expression_var.set(str(result))
            self.result_var.set("=" + str(result))
            self.previous_result = result
            self.reset_input = True
            
            # Add to history            if self.previous_input and  and self.current_input:
                expr = f"{self.previous_input} {} {self.current_input}"
                ((expr, str(result)))
                if len() > 10:  # Limit the number of history records                    (0)
                    
        except Exception as e:
            self.expression_var.set("mistake")
            self.result_var.set("")
            self.current_input = ""
            self.previous_input = ""
            self.reset_input = False
    
    @property
    def current_input(self):
        return self._current_input
    
    @current_input.setter
    def current_input(self, value):
        self._current_input = value
    
    def show_history(self):
        history_window = ()
        history_window.title("Computation History")
        history_window.geometry("400x400")
        
        history_text = (history_window, font=("Arial", 12))
        history_text.pack(fill=, expand=True, padx=10, pady=10)
        
        for expr, res in :
            history_text.insert(, f"{expr} = {res}\n")
        
        history_text.config(state=)
 
# Create the main window and run the calculatorif __name__ == "__main__":
    import math
    
    root = ()
    
    # Add custom styles    style = ()
    style.theme_use('clam')
    
    calculator = AdvancedCalculator(root)
    ()

4. Function description

4.1 Basic functions

  • Supports basic operations of addition, subtraction, multiplication and division
  • Supports brackets and decimal points
  • Clear (C) and delete (⌫) functions

4.2 Advanced scientific computing functions

  • Trigonometric functions: sin, cos, tan
  • Logarithmic function: log10
  • Square root: √
  • Power operations: x², x³, x^y
  • Constant: π, e
  • Factorial: n!
  • Inverse function: 1/x

4.3 Extra Features

  • History: Record the last 10 calculations
  • Ans function: Use the last calculation result

5. Expansion suggestions

  1. ​Graphic drawing function​​: Add function drawing function, can be integrated using matplotlib
  2. Unit conversion​: Add unit conversion functions such as length, weight, temperature, etc.
  3. ​Equation Solving​: Add solutions to quadratic equations, etc.
  4. Statistical calculations​: Add statistical functions such as mean value and standard deviation
  5. Programming mode​: Add custom function definition function

This calculator program provides complete scientific computing functions, with a simple and intuitive interface, suitable for learning and daily use.

The above is the detailed content of using Python to create a complete Windows-style calculator program. For more information about creating a Windows-style calculator program in Python, please follow my other related articles!