使用Flask構建基於Web的計算器



在這裡,我們將學習使用Python和Flask建立基於Web的計算器的分步過程。Flask易於安裝且使用簡單,非常適合小型到中型專案。對於在使用Python進行Web開發領域的新手來說,本教程是一個極好的入門方式。

我們還將回顧構建計算器介面所需的最小HTMLCSSJavaScript知識,該介面允許進行簡單的計算。

安裝

首先,在我們繼續編碼之前,我們需要確保已經安裝了Python和Flask。如果你尚未安裝Flask,可以透過pip(Python的包安裝程式)輕鬆安裝。

步驟1:安裝Python

首先,您必須在您的機器上安裝Python。您可以從官方Python網站下載。

另請閱讀:Python環境搭建

步驟2:安裝Flask

開啟命令提示符或終端,並執行以下命令:

pip install flask

使用Flask構建基於Web的計算器

我們將首先建立一個簡單的Flask應用程式,然後設計計算器的HTML介面並使用CSS進行樣式設定。

步驟1:建立Flask應用程式 (app.py)

此檔案將儲存我們Flask應用程式的主要邏輯。

app.py 程式碼

from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/", methods=["GET", "POST"])
def index():
   result = ''
   if request.method == "POST":
      try:
         expression = request.form["display"]
         # Evaluate the expression safely using eval
         result = eval(expression)
      except Exception as e:
         result = "Error"
   return render_template("index.html", result=result)

if __name__ == "__main__":
   app.run(debug=True)

程式碼解釋

讓我們首先匯入必要的模組,包括:Flask、RenderTemplate和Request。

**index()**函式處理兩種HTTP方法協議,包括GET和POST。當用戶提交表單(POST請求)時,該函式嘗試計算使用者輸入的表示式並返回該值。

如果在計算過程中出現任何問題(例如,輸入錯誤),則返回“錯誤”。

最後,我們將計算結果與index.HTML模板一起呈現。

步驟2:建立HTML模板 (index.html)

在你的專案資料夾內建立一個名為“templates”的目錄。在“templates”目錄中,建立一個名為“index.html”的檔案。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask Calculator</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div class="calculator">
   <h1>Flask Calculator</h1>
   <form method="POST">
      <input type="text" name="display" id="display" value="{{ result }}" readonly>

      <div class="buttons">
         <button type="button" class="btn" onclick="appendToDisplay('1')">1</button>
         <button type="button" class="btn" onclick="appendToDisplay('2')">2</button>
         <button type="button" class="btn" onclick="appendToDisplay('3')">3</button>
         <button type="button" class="btn operator" onclick="appendToDisplay('+')">+</button>

         <button type="button" class="btn" onclick="appendToDisplay('4')">4</button>
         <button type="button" class="btn" onclick="appendToDisplay('5')">5</button>
         <button type="button" class="btn" onclick="appendToDisplay('6')">6</button>
         <button type="button" class="btn operator" onclick="appendToDisplay('-')">-</button>

         <button type="button" class="btn" onclick="appendToDisplay('7')">7</button>
         <button type="button" class="btn" onclick="appendToDisplay('8')">8</button>
         <button type="button" class="btn" onclick="appendToDisplay('9')">9</button>
         <button type="button" class="btn operator" onclick="appendToDisplay('*')">×</button>

         <button type="button" class="btn" onclick="appendToDisplay('0')">0</button>
         <button type="button" class="btn" onclick="clearDisplay()">C</button>
         <button type="submit" class="btn operator">=</button>
         <button type="button" class="btn operator" onclick="appendToDisplay('/')">÷</button>
      </div>
   </form>
</div>

<script>
   function appendToDisplay(value) {
      const display = document.getElementById('display');
      display.value += value;
   }

   function clearDisplay() {
      document.getElementById('display').value = '';
   }
</script>
</body>
</html>

程式碼解釋

index.html 檔案定義了計算器的外觀。在這個程式中,它包含一個輸入欄位用於輸入數值和顯示結果。

它包含數字按鈕和數學運算按鈕(+,-,*,/),以及功能鍵,包括“C”鍵清除結果和“=”鍵顯示結果。

計算器上的按鈕,顯示追加和清除功能,使用 JavaScript 函式來處理按鈕互動以及顯示的更新或清除。

步驟 3:新增樣式 (style.css)

在你的專案資料夾內建立一個名為“static”的目錄。在“static”目錄中,建立一個名為“style.css”的檔案來設定計算器的樣式。

body {
   font-family: Arial, sans-serif;
   background-color: #f0f0f0;
   display: flex;
   justify-content: center;
   align-items: center;
   height: 100vh;
   margin: 0;
}

.calculator {
   width: 100%;
   max-width: 600px;
   background-color: #333;
   padding: 30px;
   border-radius: 15px;
   box-shadow: 0px 0px 15px 0px #000;
   text-align: center;
}

h1 {
   color: #fff;
   margin-bottom: 20px;
   font-size: 36px;
}

#display {
   width: 100%;
   height: 80px;
   font-size: 36px;
   text-align: right;
   padding: 15px;
   margin-bottom: 20px;
   border-radius: 10px;
   border: none;
   background-color: #222;
   color: #fff;
}

.buttons {
   display: grid;
   grid-template-columns: repeat(4, 1fr);
   gap: 15px;
}

.btn {
   width: 100%;
   padding: 30px;
   font-size: 24px;
   border: none;
   border-radius: 10px;
   background-color: #666;
   color: #fff;
   cursor: pointer;
   transition: background-color 0.2s;
}

.btn:hover {
   background-color: #555;
}

.operator {
   background-color: #ff9500;
}

.operator:hover {
   background-color: #e68a00;
}

.btn:active {
   background-color: #444;
}

.operator:active {
   background-color: #cc7a00;
}

步驟 4:執行應用程式

現在我們已經擁有了所有必要的檔案,你可以在你的專案目錄中執行以下命令來執行你的 Flask 應用程式:

python app.py

在你的網頁瀏覽器中訪問 http://127.0.0.1:5000/ 來檢視你的基於網頁的計算器。

python app

輸出

現在將 http://127.0.0.1:5000 複製到隱身視窗中貼上。

python app

現在你將看到這個介面。

web-based calculator

現在你可以使用滑鼠點選進行計算。

web-based calculator
python_projects_from_basic_to_advanced.htm
廣告