用Python編寫一個簡單的計算器

一、背景介紹

計算器是人們生活中使用頻率非常高的工具,不管是進行數學運算還是計算時間和日期,計算器都能給我們相應的幫助。Python作為一門功能強大的編程語言,為我們編寫計算器提供了非常便利的條件。在本文中,我們將介紹如何使用Python開發一個簡單的計算器。

二、設計思路

我們將使用Python的tkinter庫來實現這個計算器。其實,使用tkinter來實現圖形用戶界面非常方便。我們只需要通過導入tkinter庫,定義窗口、按鍵、事件等相關參數就能夠實現一個簡單的計算器了。

計算器主要分為兩個部分:顯示屏和操作部件。其中,操作部件包括數字鍵、運算符鍵和控制鍵。具體而言,我們需要添加10個數字鍵,按鍵0~9,加減乘除四個運算符和其他的控制鍵,如等於鍵、清楚鍵等。同時,還需要在窗口中顯示當前的計算結果。

三、代碼實現


from tkinter import *

class Calculator:
    def __init__(self):
        self.root = Tk()  # 創建一個頂層窗口
        self.root.title("計算器")  # 窗口標題
        self.result = StringVar()  # 創建一個用於顯示結果的變數
        self.result.set('')  # 設置默認顯示為空
        self.entry = Entry(self.root, textvariable=self.result, bd=3, bg='white', justify='right')
        self.entry.grid(row=0, column=0, columnspan=4, pady=5)  # 顯示屏的位置和樣式
        # 創建「C」按鈕
        clear_button = Button(self.root, text='C', width=5, height=2, command=self.clear)
        clear_button.grid(row=1, column=0)
        # 創建等於「=」按鈕
        equal_button = Button(self.root, text='=', width=5, height=2, command=self.calculate)
        equal_button.grid(row=1, column=3)
        # 創建數字按鈕
        button_1 = Button(self.root, text='1', width=5, height=2, command=lambda: self.input_number('1'))
        button_1.grid(row=2, column=0)
        button_2 = Button(self.root, text='2', width=5, height=2, command=lambda: self.input_number('2'))
        button_2.grid(row=2, column=1)
        button_3 = Button(self.root, text='3', width=5, height=2, command=lambda: self.input_number('3'))
        button_3.grid(row=2, column=2)
        button_4 = Button(self.root, text='4', width=5, height=2, command=lambda: self.input_number('4'))
        button_4.grid(row=3, column=0)
        button_5 = Button(self.root, text='5', width=5, height=2, command=lambda: self.input_number('5'))
        button_5.grid(row=3, column=1)
        button_6 = Button(self.root, text='6', width=5, height=2, command=lambda: self.input_number('6'))
        button_6.grid(row=3, column=2)
        button_7 = Button(self.root, text='7', width=5, height=2, command=lambda: self.input_number('7'))
        button_7.grid(row=4, column=0)
        button_8 = Button(self.root, text='8', width=5, height=2, command=lambda: self.input_number('8'))
        button_8.grid(row=4, column=1)
        button_9 = Button(self.root, text='9', width=5, height=2, command=lambda: self.input_number('9'))
        button_9.grid(row=4, column=2)
        button_0 = Button(self.root, text='0', width=12, height=2, command=lambda: self.input_number('0'))
        button_0.grid(row=5, column=0, columnspan=2)
        # 創建運算符按鈕
        button_add = Button(self.root, text='+', width=5, height=2, command=lambda: self.input_op('+'))
        button_add.grid(row=2, column=3)
        button_minus = Button(self.root, text='-', width=5, height=2, command=lambda: self.input_op('-'))
        button_minus.grid(row=3, column=3)
        button_multiply = Button(self.root, text='*', width=5, height=2, command=lambda: self.input_op('*'))
        button_multiply.grid(row=4, column=3)
        button_divide = Button(self.root, text='/', width=5, height=2, command=lambda: self.input_op('/'))
        button_divide.grid(row=5, column=3)
        self.root.mainloop()  # 進入消息循環

    def input_number(self, number):
        current = self.result.get()
        self.result.set(current + str(number))

    def input_op(self, op):
        current = self.result.get()
        if current.endswith(('/', '*', '-', '+')) or current == '':
            pass  # 如果當前為空或以運算符結尾則無效
        else:
            self.result.set(current + op)

    def clear(self):
        self.result.set('')

    def calculate(self):
        expression = self.result.get()
        if expression == '':
            return
        elif expression.endswith(('/', '*', '-', '+')):
            expression = expression[:-1]  # 去除末尾的運算符
        else:
            pass
        self.result.set(eval(expression))

四、源碼分析

為了實現一個簡單的計算器,我們首先需要創建一個頂層窗口,然後在窗口中添加顯示屏和操作部件,使其具備數字輸入、運算和結果顯示等功能。

首先,我們定義一個Calculator類,它包含創建窗口和添加控制項的各個方法。在構造函數中,我們創建了一個名為result的字元串變數,並設置其默認值為空。接著,我們創建了顯示屏entry,並將其與result綁定,以便顯示在窗口中。

接下來,我們創建了「C」鍵和「=」鍵的Button按鈕,並分別綁定清除和計算方法。然後,我們創建了10個數字按鈕,將它們分別綁定到數字的Lambda函數上,以便可以輸入數字。最後,我們創建了4個與運算符相關的按鈕,並使用與定義數字相似的Lambda函數將它們綁定到相應的操作方法上。

在Calculator類中,我們還實現了四個方法。input_number()方法負責將數字鍵添加到當前顯示屏上;input_op()方法用於添加運算符;clear()方法用於清除屏幕上的內容;calculate()方法用於計算表達式並顯示結果。

五、使用方法

使用Python編寫的計算器非常易於使用。只需單擊數字鍵進行輸入,單擊運算符鍵進行計算,單擊「C」「AC」鍵進行清除。當然,您也可以使用鍵盤輸入數字和運算符,並按Enter鍵來進行計算。這種實現方法甚至比其他計算器更直觀、更簡單。

六、總結

在本文中,我們介紹了如何使用Python和tkinter庫來編寫一個簡單的計算器程序。我們使用Python的面向對象編程風格,定義了一個Calculator類,並在窗口中添加了各種控制項來實現計算器的各種功能。使用Python編寫計算器程序非常簡單,並且可以自由地擴展其功能,使其符合您的需求。

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/300987.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-29 14:19
下一篇 2024-12-29 14:19

相關推薦

  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智慧、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • 蝴蝶優化演算法Python版

    蝴蝶優化演算法是一種基於仿生學的優化演算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化演算法Python版…

    編程 2025-04-29

發表回復

登錄後才能評論