如何用Tkinter構建一個貨幣轉換器GUI

如何用Tkinter建立一個貨幣轉換器GUI

Tkinter 是一個內建的 Python 庫,用於建立圖形使用者介面 (GUI)。它提供了一套用於建立視窗、框架、按鈕、文字框和其他GUI元素的工具。

它很容易使用,而且廣泛可用,使它成為在Python中構建GUI應用程式的熱門選擇。它也是高度可定製的,允許開發者建立獨特的、具有視覺吸引力的使用者介面。

在本教程中,你將使用Tkinter構建一個貨幣轉換器GUI應用程式。

下面是你的最終結果的樣子:

貨幣轉換器GUI應用程式

你可以在這個資源庫中找到該教程的程式碼。

先決條件

要繼續學習本教程並構建應用程式,你應該具備以下條件:

  • 具有Python程式語言的基本知識
  • 在你的系統上安裝了Python 3.8以上版本
  • 熟悉Tkinter和Requests庫

如何設定你的虛擬環境

在你開始編碼之前,你需要確保你安裝了所有必要的工具和庫。為了確保你有一個乾淨和隔離的環境,你將使用venv建立一個虛擬環境。

建立一個專案目錄並在終端導航到它:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mkdir currency-converter
cd currency-converter
mkdir currency-converter cd currency-converter
mkdir currency-converter
cd currency-converter

使用以下命令建立一個名為 env 的虛擬環境:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
python -m venv env
python -m venv env
python -m venv env

現在Python帶有預裝的 venv 庫,用於建立虛擬環境。

像這樣啟用虛擬環境:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
source env/bin/activate
source env/bin/activate
source env/bin/activate

注意:如果你在Windows上,你需要使用 source env/Scripts/activate 來啟用這個環境。

你應該在你的終端提示中看到 (env) ,表明虛擬環境已經被啟用。

如何安裝庫

現在你已經建立了虛擬環境,你可以安裝以下庫:

  • requests: 該庫幫助你在API端點上傳送請求。
  • python-decouple: 該庫幫助你讀取環境變數的值。
  • pillow: 該庫幫助你讀取環境變數的值: 該庫為你的Python直譯器增加了影象處理能力。

要安裝這些庫,請執行以下命令:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install requests python-decouple pillow
pip install requests python-decouple pillow
pip install requests python-decouple pillow

如何構建貨幣轉換器的實用功能

在本節中,你將開始構建我們的貨幣轉換器GUI的核心功能。你將建立兩個實用函式,用於轉換貨幣和從JSON檔案中檢索貨幣程式碼。

為了定義這些實用功能,你將在專案中建立一個名為 utils.py 的新檔案。這個檔案將包含你的貨幣轉換器GUI的所有實用函式。

從JSON檔案中獲取貨幣程式碼的實用函式

這個實用函式將從JSON檔案中獲取貨幣程式碼。這個函式將允許你用使用者可以選擇的可用貨幣列表來填充GUI。

建立一個 currency.json 檔案,包括各種貨幣的貨幣程式碼和名稱。該JSON檔案有以下結構:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[
{ "AED": "United Arab Emirates Dirham" },
{ "AFN": "Afghan Afghani" },
{ "ALL": "Albanian Lek" },
...
]
[ { "AED": "United Arab Emirates Dirham" }, { "AFN": "Afghan Afghani" }, { "ALL": "Albanian Lek" }, ... ]
[
{ "AED": "United Arab Emirates Dirham" },
{ "AFN": "Afghan Afghani" },
{ "ALL": "Albanian Lek" },
...
]

你可以從這個連結中獲得 currency.json 檔案的內容,並將其複製到你的專案中的 currency.json 檔案。

新增以下程式碼來定義第一個實用函式:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import json
def get_currencies() -> list:
currency_codes = []
with open('currency.json') as f:
currency_data = json.load(f)
for currency in currency_data:
code, _ = list(currency.items())[0]
currency_codes.append(code)
return sorted(currency_codes
import json def get_currencies() -> list: currency_codes = [] with open('currency.json') as f: currency_data = json.load(f) for currency in currency_data: code, _ = list(currency.items())[0] currency_codes.append(code) return sorted(currency_codes
import json
def get_currencies() -> list:
currency_codes = []
with open('currency.json') as f:
currency_data = json.load(f)
for currency in currency_data:
code, _ = list(currency.items())[0]
currency_codes.append(code)
return sorted(currency_codes

在上面的程式碼中,你定義了一個 get_currencies() 函式,用來返回一個貨幣程式碼的列表。在該函式中,你建立了一個名為 currency_codes 的空列表,你將用它來儲存貨幣程式碼。然後,在讀取模式下開啟 currency.json 檔案,使用 json.load() 方法將該檔案的內容載入到一個叫做 currency_data 的 Python 字典中。

接下來,使用 for 迴圈遍歷 currency_data 字典中的每個專案。currency_data 字典中的每個專案本身就是一個字典,有一個代表貨幣程式碼及其名稱的鍵值對。在 for 迴圈中,你使用 list() 函式將每種貨幣的鍵值對轉換為一個列表。

由於每個 dictionary 只包含一個鍵值對,我們可以使用 items() 方法將 dictionary 轉換為包含鍵值對的元組列表。

然後你使用元組解包,將列表中的第一個元素分配給 code 變數,並使用 _ 忽略第二個元素。

最後,你將代表貨幣程式碼的 code 變數追加到 currency_codes 列表中。在迴圈瀏覽 currency_data 中的所有貨幣後,使用 sorted() 函式將 currency_codes 列表按升序排序,並從該函式中返回。

如果你呼叫該函式並列印其結果,你將得到以下輸出:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
['ADA', 'AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AVAX', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BNB', 'BND', 'BOB', 'BRL', 'BSD', 'BTC', 'BTN', 'BWP', 'BYN', 'BYR', 'BZD', 'CAD', 'CDF', 'CHF', 'CLF', 'CLP', 'CNY', 'COP', 'CRC', 'CUC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DOT', 'DZD', 'EGP', 'ERN', 'ETB', 'ETH', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GGP', 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'IMP', 'INR', 'IQD', 'IRR', 'ISK', 'JEP', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LTC', 'LTL', 'LVL', 'LYD', 'MAD', 'MATIC', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT', 'MOP', 'MRO', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOL', 'SOS', 'SRD', 'STD', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VEF', 'VND', 'VUV', 'WST', 'XAF', 'XAG', 'XAU', 'XCD', 'XDR', 'XOF', 'XPF', 'XRP', 'YER', 'ZAR', 'ZMK', 'ZMW', 'ZWL']
['ADA', 'AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AVAX', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BNB', 'BND', 'BOB', 'BRL', 'BSD', 'BTC', 'BTN', 'BWP', 'BYN', 'BYR', 'BZD', 'CAD', 'CDF', 'CHF', 'CLF', 'CLP', 'CNY', 'COP', 'CRC', 'CUC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DOT', 'DZD', 'EGP', 'ERN', 'ETB', 'ETH', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GGP', 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'IMP', 'INR', 'IQD', 'IRR', 'ISK', 'JEP', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LTC', 'LTL', 'LVL', 'LYD', 'MAD', 'MATIC', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT', 'MOP', 'MRO', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOL', 'SOS', 'SRD', 'STD', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VEF', 'VND', 'VUV', 'WST', 'XAF', 'XAG', 'XAU', 'XCD', 'XDR', 'XOF', 'XPF', 'XRP', 'YER', 'ZAR', 'ZMK', 'ZMW', 'ZWL']
['ADA', 'AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AVAX', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BNB', 'BND', 'BOB', 'BRL', 'BSD', 'BTC', 'BTN', 'BWP', 'BYN', 'BYR', 'BZD', 'CAD', 'CDF', 'CHF', 'CLF', 'CLP', 'CNY', 'COP', 'CRC', 'CUC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DOT', 'DZD', 'EGP', 'ERN', 'ETB', 'ETH', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GGP', 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'IMP', 'INR', 'IQD', 'IRR', 'ISK', 'JEP', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LTC', 'LTL', 'LVL', 'LYD', 'MAD', 'MATIC', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT', 'MOP', 'MRO', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOL', 'SOS', 'SRD', 'STD', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VEF', 'VND', 'VUV', 'WST', 'XAF', 'XAG', 'XAU', 'XCD', 'XDR', 'XOF', 'XPF', 'XRP', 'YER', 'ZAR', 'ZMK', 'ZMW', 'ZWL']

轉換貨幣的實用函式

為了建立貨幣轉換器,你需要一個可以將一種貨幣轉換成另一種貨幣的實用函式。為此,你將使用一個外部API來獲取最新的貨幣兌換值。雖然有許多貨幣兌換API可用,如API ForexForex API等,但你要使用Currency Conversion API

你可以通過使用 requests 模組或其自身的 currencyapi-python 庫將該API整合到你的程式碼中。如前所述,你將在本教程中使用請求模組。

要使用該API,你需要註冊一個API金鑰。你可以在 https://app.currencyapi.com/register 註冊一個免費賬戶。一旦你註冊了,你可以在儀表板頁面上找到你的API金鑰(用黑色突出顯示)。

currencyapi網站截圖

建立一個 .env 檔案並新增以下程式碼來設定環境變數:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
export API_KEY='your-api-key-here'
export API_KEY='your-api-key-here'
export API_KEY='your-api-key-here'

從儀表板上覆制你的API金鑰,並在上述檔案中替換 your-api-key-here 。然後執行以下命令來設定環境變數:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
source .env
source .env
source .env

然後你在Python程式碼中使用 python-decouple 庫來讀取API金鑰值。

接下來,在同一個 utils.py 檔案中,新增以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import requests
from decouple import config
API_KEY = config('API_KEY')
API_ENDPOINT = 'https://api.currencyapi.com/v3/latest'
def convert_currency(from_currency: str, to_currency: str, amount: float) -> float:
query_params = {
'apikey': API_KEY,
'base_currency': from_currency,
'currencies': to_currency
}
response = requests.get(API_ENDPOINT, params=query_params)
currency_data = response.json()
exchange_rate = currency_data['data'][to_currency]['value']
exchanged_value = exchange_rate * amount
return exchanged_value
import requests from decouple import config API_KEY = config('API_KEY') API_ENDPOINT = 'https://api.currencyapi.com/v3/latest' def convert_currency(from_currency: str, to_currency: str, amount: float) -> float: query_params = { 'apikey': API_KEY, 'base_currency': from_currency, 'currencies': to_currency } response = requests.get(API_ENDPOINT, params=query_params) currency_data = response.json() exchange_rate = currency_data['data'][to_currency]['value'] exchanged_value = exchange_rate * amount return exchanged_value
import requests
from decouple import config
API_KEY = config('API_KEY')
API_ENDPOINT = 'https://api.currencyapi.com/v3/latest'
def convert_currency(from_currency: str, to_currency: str, amount: float) -> float:
query_params = {
'apikey': API_KEY,
'base_currency': from_currency,
'currencies': to_currency
}
response = requests.get(API_ENDPOINT, params=query_params)
currency_data = response.json()
exchange_rate = currency_data['data'][to_currency]['value']
exchanged_value = exchange_rate * amount
return exchanged_value

convert_currency 函式需要三個引數:from_currencyto_currency, 和 amount。 from_currency 和 to_currency 是被轉換貨幣的ISO貨幣程式碼,amount 是你要轉換的 from_currency 的金額。

該函式向 API_ENDPOINT URL傳送一個GET請求,將 API_KEYfrom_currency, 和 to_currency 作為查詢引數。requests 模組的 requests.get() 函式被用來傳送請求,params 引數被用來傳遞查詢引數。

一旦收到響應,我們使用 response 物件的 json() 方法將其轉換成 Python 字典。一個成功的響應樣本看起來像這樣:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"meta":{
"last_updated_at":"2023-03-30T23:59:59Z"
},
"data":{
"INR":{
"code":"INR",
"value":82.100841
}
}
}
{ "meta":{ "last_updated_at":"2023-03-30T23:59:59Z" }, "data":{ "INR":{ "code":"INR", "value":82.100841 } } }
{
"meta":{
"last_updated_at":"2023-03-30T23:59:59Z"
},
"data":{
"INR":{
"code":"INR",
"value":82.100841
}
}
}

然後從響應字典中提取匯率,用 amount 和 exchange_rate計算出交換值。最後,你返回交換的值。

如何用Tkinter設計貨幣轉換器的GUI

現在你已經準備好了實用功能,你可以用Tkinter設計GUI。下面是這個應用程式的樣子:

設計貨幣轉換器的GUI

該設計包括一個300 X 320尺寸的視窗,有一個頂框和一個主框。頂部框架包含應用程式的圖示和標題。主框架包括標籤、組合框、輸入小部件和貨幣轉換按鈕。

讓我們一步一步地建立這個應用程式。在專案目錄下建立一個 main.py 檔案。首先,匯入必要的模組和函式,以及定義一些顏色常數。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from tkinter import *
from tkinter import Tk, ttk
from PIL import Image, ImageTk
from utils import convert_currency, get_currencies
# Colors
WHITE_COLOR = "#FFFFFF"
BLACK_COLOR = "#333333"
BLUE_COLOR = "#0000FF"
from tkinter import * from tkinter import Tk, ttk from PIL import Image, ImageTk from utils import convert_currency, get_currencies # Colors WHITE_COLOR = "#FFFFFF" BLACK_COLOR = "#333333" BLUE_COLOR = "#0000FF"
from tkinter import *
from tkinter import Tk, ttk
from PIL import Image, ImageTk
from utils import convert_currency, get_currencies
# Colors
WHITE_COLOR = "#FFFFFF"
BLACK_COLOR = "#333333"
BLUE_COLOR = "#0000FF"

如何建立視窗

當用Tkinter建立一個GUI應用程式時,第一步是建立一個具有特定大小和標題的視窗。在本例中,視窗的大小應該被設定為300×320,標題應該是 “Currency Converter(貨幣轉換器)”。預設情況下,視窗的背景顏色是白色的,而且它不應該是可調整大小的。下面是程式碼:

# Window Configuration
window = Tk()
window.geometry("300x320")
window.title("Currency Converter")
window.configure(bg=WHITE_COLOR)
window.resizable(height=FALSE, width=FALSE)

如何建立框架

如前所述,你需要建立兩個框架–一個頂部框架和一個主框架。頂層框架將包含應用程式的圖示和標題,而主框架將包括基本部件,如標籤、輸入部件、組合框和轉換按鈕。下面的程式碼完成了這個任務:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Create top and main frames
top_frame = Frame(window, width=300, height=60, bg=BLUE_COLOR)
top_frame.grid(row=0, column=0)
main_frame = Frame(window, width=300, height=260, bg=WHITE_COLOR)
main_frame.grid(row=1, column=0)
# Create top and main frames top_frame = Frame(window, width=300, height=60, bg=BLUE_COLOR) top_frame.grid(row=0, column=0) main_frame = Frame(window, width=300, height=260, bg=WHITE_COLOR) main_frame.grid(row=1, column=0)
# Create top and main frames
top_frame = Frame(window, width=300, height=60, bg=BLUE_COLOR)
top_frame.grid(row=0, column=0)
main_frame = Frame(window, width=300, height=260, bg=WHITE_COLOR)
main_frame.grid(row=1, column=0)

這裡,Frame() 函式被用來建立兩個框架。第一個引數是父視窗(本例中是 window ),然後是框架的寬度、高度和背景顏色。然後,你可以使用 grid() 方法,通過指定框架的行和列的位置,把它們放在視窗中。

你把 top_frame  widget放在網格的第一行和第一列,而把 main_frame widget放在網格的第二行和第一列。

如何在頂部框架中新增Widget

之後,你可以建立屬於頂框的小部件。如前所述,頂層框架應該有一個應用程式圖示和應用程式標題。你可以從Icons8(或從這裡)獲得一個圖示,並將其儲存在你的專案目錄下,名稱為 icon.png

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Top Frame Widgets
icon_image = Image.open('icon.png')
icon_image = icon_image.resize((40, 40))
icon_image = ImageTk.PhotoImage(icon_image)
app_name_label = Label(top_frame, image=icon_image, compound=LEFT, text="Currency Converter", height=3, padx=13, pady=30, anchor=CENTER, font=('Arial 16 bold'), bg=BLUE_COLOR, fg=WHITE_COLOR)
app_name_label.place(x=0, y=0)
# Top Frame Widgets icon_image = Image.open('icon.png') icon_image = icon_image.resize((40, 40)) icon_image = ImageTk.PhotoImage(icon_image) app_name_label = Label(top_frame, image=icon_image, compound=LEFT, text="Currency Converter", height=3, padx=13, pady=30, anchor=CENTER, font=('Arial 16 bold'), bg=BLUE_COLOR, fg=WHITE_COLOR) app_name_label.place(x=0, y=0)
# Top Frame Widgets
icon_image = Image.open('icon.png')
icon_image = icon_image.resize((40, 40))
icon_image = ImageTk.PhotoImage(icon_image)
app_name_label = Label(top_frame, image=icon_image, compound=LEFT, text="Currency Converter", height=3, padx=13, pady=30, anchor=CENTER, font=('Arial 16 bold'), bg=BLUE_COLOR, fg=WHITE_COLOR)
app_name_label.place(x=0, y=0)

該程式碼首先使用PIL(Python影象庫)模組的 Image 類開啟影象檔案 icon.png。然後使用 resize() 方法將影象的大小調整為40×40。接下來,它使用 ImageTk 模組的 PhotoImage 類將影象轉換為可以在GUI中顯示的格式。

下一行建立了一個顯示應用程式圖示和標題的 Label 小部件。你在頂層框架內建立這個部件。該小元件需要幾個引數來配置它的外觀。

這些引數包括以下內容:

  • 應用程式圖示的 image
  • 要顯示的 text(”Currency Converter”)。
  • 標籤的 height(設定為3)
  • 左側和頂部的填充(分別設定為13和30)
  • 標籤的錨點(設定為中心)。
  • 字型風格 (Arial 16 bold)
  • 背景顏色 (設定為 BLUE_COLOR)
  • 前景顏色 (設定為 WHITE_COLOR)

最後,我們使用 place() 方法來設定標籤在頂部框架中的位置。

如何在主框架中新增小工具

如前所述,主框架將包含基本的小工具。讓我們一步一步地建立它們。

下面的程式碼在 main_frame 框架內建立了一個名為 result_label 的標籤小部件。這個標籤將顯示貨幣轉換的結果。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
result_label = Label(main_frame, text=" ", width=15, height=2, pady=7, padx=0, anchor=CENTER, font=('Ivy 16 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=SOLID)
result_label.place(x=50, y=10)
result_label = Label(main_frame, text=" ", width=15, height=2, pady=7, padx=0, anchor=CENTER, font=('Ivy 16 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=SOLID) result_label.place(x=50, y=10)
result_label = Label(main_frame, text=" ", width=15, height=2, pady=7, padx=0, anchor=CENTER, font=('Ivy 16 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=SOLID)
result_label.place(x=50, y=10)

該標籤的文字設定為空字串(” “),寬度為15,高度為2行,Y軸上的填充物為7畫素,X軸上的填充物為0畫素。文字將使用 anchor=CENTER 選項居中,使用的字型是 Ivy 16 bold。標籤的背景顏色被設定為白色(bg=WHITE_COLOR),文字顏色為黑色(fg=BLACK_COLOR)。relief 選項被設定為SOLID,以使標籤具有邊界。最後,使用 place() 方法將標籤放在座標(50, 10)處。

接下來,在應用程式的設計中,有兩個標籤–“From “和 “To”,每個標籤的下面都有一個 ComboBox

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from_label = Label(main_frame, text="From", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT)
from_label.place(x=48, y=90)
from_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),)
from_combo['values'] = (get_currencies())
from_combo.current(0)
from_combo.place(x=50, y=115)
to_label = Label(main_frame, text="To", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT)
to_label.place(x=158, y=90)
to_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),)
to_combo['values'] = (get_currencies())
to_combo.current(1)
to_combo.place(x=160, y=115)
from_label = Label(main_frame, text="From", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT) from_label.place(x=48, y=90) from_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),) from_combo['values'] = (get_currencies()) from_combo.current(0) from_combo.place(x=50, y=115) to_label = Label(main_frame, text="To", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT) to_label.place(x=158, y=90) to_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),) to_combo['values'] = (get_currencies()) to_combo.current(1) to_combo.place(x=160, y=115)
from_label = Label(main_frame, text="From", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT)
from_label.place(x=48, y=90)
from_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),)
from_combo['values'] = (get_currencies())
from_combo.current(0)
from_combo.place(x=50, y=115)
to_label = Label(main_frame, text="To", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT)
to_label.place(x=158, y=90)
to_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),)
to_combo['values'] = (get_currencies())
to_combo.current(1)
to_combo.place(x=160, y=115)

第一個 Label 和 ComboBox 是用來轉換貨幣的。你使用 Label() 函式建立標籤,並指定文字、寬度、高度、填充、字型和顏色設定。然後使用place()函式將Label放置在主框架的指定座標處。

然後使用 ttk.Combobox() 函式建立一個 ComboBox,並指定寬度、字型和對齊方式。使用 get_currencies() 函式(從 utils.py 匯入)設定 ComboBox 的可用值,使用 current() 函式將預設值設定為列表中的第一個專案。使用 place() 函式,ComboBox 也被放置在主框架的指定座標處。

第二個Label和ComboBox是用來轉換貨幣的。Label和ComboBox的建立和放置方式與第一個Label和ComboBox類似,唯一的區別是文字和放置座標。

應用程式設計中的最後兩個部件是輸入欄位和轉換按鈕。你可以使用 Entry() 方法來建立輸入欄位。它需要幾個引數,包括 widthjustifyfont, 和 relief。然後使用place()方法將建立的部件以特定的座標放在主框架上。

同樣地,轉換按鈕也是用 Button() 方法建立的。它需要幾個引數,如 textwidthheightbgfgfont, 和 command。然後使用 place() 方法將建立的按鈕放在主框架的特定座標上。

下面是建立輸入欄和轉換按鈕的程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
amount_entry = Entry(main_frame, width=22, justify=CENTER,
font=('Ivy 12 bold'), relief=SOLID)
amount_entry.place(x=50, y=155)
convert_button = Button(main_frame, text="Convert", width=19, padx=5,
height=1, bg=BLUE_COLOR, fg=WHITE_COLOR, font=('Ivy 12 bold'), command=convert)
convert_button.place(x=50, y=210)
amount_entry = Entry(main_frame, width=22, justify=CENTER, font=('Ivy 12 bold'), relief=SOLID) amount_entry.place(x=50, y=155) convert_button = Button(main_frame, text="Convert", width=19, padx=5, height=1, bg=BLUE_COLOR, fg=WHITE_COLOR, font=('Ivy 12 bold'), command=convert) convert_button.place(x=50, y=210)
amount_entry = Entry(main_frame, width=22, justify=CENTER,
font=('Ivy 12 bold'), relief=SOLID)
amount_entry.place(x=50, y=155)
convert_button = Button(main_frame, text="Convert", width=19, padx=5,
height=1, bg=BLUE_COLOR, fg=WHITE_COLOR, font=('Ivy 12 bold'), command=convert)
convert_button.place(x=50, y=210)

convert_button 部件中的 command 引數需要一個函式名稱。在這種情況下,它被設定為 convert。但是 convert 函式還沒有被定義。要定義它,你可以在視窗被定義之前新增以下程式碼:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
def convert():
amount = float(amount_entry.get())
from_currency = from_combo.get()
to_currency = to_combo.get()
converted_amount = convert_currency(from_currency, to_currency, amount)
result_label['text'] = f'{to_currency} {converted_amount:.2f}'
def convert(): amount = float(amount_entry.get()) from_currency = from_combo.get() to_currency = to_combo.get() converted_amount = convert_currency(from_currency, to_currency, amount) result_label['text'] = f'{to_currency} {converted_amount:.2f}'
def convert():
amount = float(amount_entry.get())
from_currency = from_combo.get()
to_currency = to_combo.get()
converted_amount = convert_currency(from_currency, to_currency, amount)
result_label['text'] = f'{to_currency} {converted_amount:.2f}'

convert 函式從 amount_entry 部件中獲取使用者輸入,從 from_combo 和 to_combo 部件中獲取選定的貨幣,並將它們傳遞給 convert_currency 函式(從 utils.py) 中匯入)以獲得轉換後的金額。然後,它將 text 的值設定為 result_label 部件中的兌換值。

最後,你在檔案的最後呼叫 mainloop() 方法。該方法負責執行應用程式,不斷檢查使用者事件,如滑鼠點選、鍵盤輸入和視窗大小的調整,並在必要時更新視窗。

一旦 mainloop() 方法被呼叫,程式就進入事件迴圈,開始等待使用者事件。視窗將保持開放和活躍,直到使用者關閉視窗或程式被終止。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Mainloop
window.mainloop()
# Mainloop window.mainloop()
# Mainloop
window.mainloop()

最終程式碼

這裡是你一直在構建的貨幣轉換器GUI應用程式的最終程式碼。這段程式碼包含了我們到目前為止討論過的所有不同的元件,包括建立框架、標籤、組合框、輸入欄位和按鈕。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from tkinter import *
from tkinter import Tk, ttk
from PIL import Image, ImageTk
from utils import convert_currency, get_currencies
# Colors
WHITE_COLOR = "#FFFFFF"
BLACK_COLOR = "#333333"
BLUE_COLOR = "#0000FF"
def convert():
amount = float(amount_entry.get())
from_currency = from_combo.get()
to_currency = to_combo.get()
converted_amount = convert_currency(from_currency, to_currency, amount)
result_label['text'] = f'{to_currency} {converted_amount:.2f}'
# Window Configuration
window = Tk()
window.geometry("300x320")
window.title("Currency Converter")
window.configure(bg=WHITE_COLOR)
window.resizable(height=FALSE, width=FALSE)
# Frames
top_frame = Frame(window, width=300, height=60, bg=BLUE_COLOR)
top_frame.grid(row=0, column=0)
main_frame = Frame(window, width=300, height=260, bg=WHITE_COLOR)
main_frame.grid(row=1, column=0)
# Top Frame Widgets
icon_image = Image.open('icon.png')
icon_image = icon_image.resize((40, 40))
icon_image = ImageTk.PhotoImage(icon_image)
app_name_label = Label(top_frame, image=icon_image, compound=LEFT, text="Currency Converter", height=3, padx=13, pady=30, anchor=CENTER, font=('Arial 16 bold'), bg=BLUE_COLOR, fg=WHITE_COLOR)
app_name_label.place(x=0, y=0)
# Main Frame Widgets
result_label = Label(main_frame, text=" ", width=15, height=2, pady=7, padx=0, anchor=CENTER, font=('Ivy 16 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=SOLID)
result_label.place(x=50, y=10)
from_label = Label(main_frame, text="From", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT)
from_label.place(x=48, y=90)
from_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),)
from_combo['values'] = (get_currencies())
from_combo.current(0)
from_combo.place(x=50, y=115)
to_label = Label(main_frame, text="To", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT)
to_label.place(x=158, y=90)
to_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),)
to_combo['values'] = (get_currencies())
to_combo.current(1)
to_combo.place(x=160, y=115)
amount_entry = Entry(main_frame, width=22, justify=CENTER,
font=('Ivy 12 bold'), relief=SOLID)
amount_entry.place(x=50, y=155)
convert_button = Button(main_frame, text="Convert", width=19, padx=5,
height=1, bg=BLUE_COLOR, fg=WHITE_COLOR, font=('Ivy 12 bold'), command=convert)
convert_button.place(x=50, y=210)
# Mainloop
window.mainloop()
from tkinter import * from tkinter import Tk, ttk from PIL import Image, ImageTk from utils import convert_currency, get_currencies # Colors WHITE_COLOR = "#FFFFFF" BLACK_COLOR = "#333333" BLUE_COLOR = "#0000FF" def convert(): amount = float(amount_entry.get()) from_currency = from_combo.get() to_currency = to_combo.get() converted_amount = convert_currency(from_currency, to_currency, amount) result_label['text'] = f'{to_currency} {converted_amount:.2f}' # Window Configuration window = Tk() window.geometry("300x320") window.title("Currency Converter") window.configure(bg=WHITE_COLOR) window.resizable(height=FALSE, width=FALSE) # Frames top_frame = Frame(window, width=300, height=60, bg=BLUE_COLOR) top_frame.grid(row=0, column=0) main_frame = Frame(window, width=300, height=260, bg=WHITE_COLOR) main_frame.grid(row=1, column=0) # Top Frame Widgets icon_image = Image.open('icon.png') icon_image = icon_image.resize((40, 40)) icon_image = ImageTk.PhotoImage(icon_image) app_name_label = Label(top_frame, image=icon_image, compound=LEFT, text="Currency Converter", height=3, padx=13, pady=30, anchor=CENTER, font=('Arial 16 bold'), bg=BLUE_COLOR, fg=WHITE_COLOR) app_name_label.place(x=0, y=0) # Main Frame Widgets result_label = Label(main_frame, text=" ", width=15, height=2, pady=7, padx=0, anchor=CENTER, font=('Ivy 16 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=SOLID) result_label.place(x=50, y=10) from_label = Label(main_frame, text="From", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT) from_label.place(x=48, y=90) from_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),) from_combo['values'] = (get_currencies()) from_combo.current(0) from_combo.place(x=50, y=115) to_label = Label(main_frame, text="To", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT) to_label.place(x=158, y=90) to_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),) to_combo['values'] = (get_currencies()) to_combo.current(1) to_combo.place(x=160, y=115) amount_entry = Entry(main_frame, width=22, justify=CENTER, font=('Ivy 12 bold'), relief=SOLID) amount_entry.place(x=50, y=155) convert_button = Button(main_frame, text="Convert", width=19, padx=5, height=1, bg=BLUE_COLOR, fg=WHITE_COLOR, font=('Ivy 12 bold'), command=convert) convert_button.place(x=50, y=210) # Mainloop window.mainloop()
from tkinter import *
from tkinter import Tk, ttk
from PIL import Image, ImageTk
from utils import convert_currency, get_currencies
# Colors
WHITE_COLOR = "#FFFFFF"
BLACK_COLOR = "#333333"
BLUE_COLOR = "#0000FF"
def convert():
amount = float(amount_entry.get())
from_currency = from_combo.get()
to_currency = to_combo.get()
converted_amount = convert_currency(from_currency, to_currency, amount)
result_label['text'] = f'{to_currency} {converted_amount:.2f}'
# Window Configuration
window = Tk()
window.geometry("300x320")
window.title("Currency Converter")
window.configure(bg=WHITE_COLOR)
window.resizable(height=FALSE, width=FALSE)
# Frames
top_frame = Frame(window, width=300, height=60, bg=BLUE_COLOR)
top_frame.grid(row=0, column=0)
main_frame = Frame(window, width=300, height=260, bg=WHITE_COLOR)
main_frame.grid(row=1, column=0)
# Top Frame Widgets
icon_image = Image.open('icon.png')
icon_image = icon_image.resize((40, 40))
icon_image = ImageTk.PhotoImage(icon_image)
app_name_label = Label(top_frame, image=icon_image, compound=LEFT, text="Currency Converter", height=3, padx=13, pady=30, anchor=CENTER, font=('Arial 16 bold'), bg=BLUE_COLOR, fg=WHITE_COLOR)
app_name_label.place(x=0, y=0)
# Main Frame Widgets
result_label = Label(main_frame, text=" ", width=15, height=2, pady=7, padx=0, anchor=CENTER, font=('Ivy 16 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=SOLID)
result_label.place(x=50, y=10)
from_label = Label(main_frame, text="From", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT)
from_label.place(x=48, y=90)
from_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),)
from_combo['values'] = (get_currencies())
from_combo.current(0)
from_combo.place(x=50, y=115)
to_label = Label(main_frame, text="To", width=8, height=1, pady=0, padx=0, anchor=NW, font=('Ivy 10 bold'), bg=WHITE_COLOR, fg=BLACK_COLOR, relief=FLAT)
to_label.place(x=158, y=90)
to_combo = ttk.Combobox(main_frame, width=8, justify=CENTER, font=('Ivy 12 bold'),)
to_combo['values'] = (get_currencies())
to_combo.current(1)
to_combo.place(x=160, y=115)
amount_entry = Entry(main_frame, width=22, justify=CENTER,
font=('Ivy 12 bold'), relief=SOLID)
amount_entry.place(x=50, y=155)
convert_button = Button(main_frame, text="Convert", width=19, padx=5,
height=1, bg=BLUE_COLOR, fg=WHITE_COLOR, font=('Ivy 12 bold'), command=convert)
convert_button.place(x=50, y=210)
# Mainloop
window.mainloop()

你終於可以執行應用程式並開始轉換貨幣了!

小結

在本教程中,你學會了如何使用Python和Tkinter建立一個簡單的貨幣轉換器應用程式。我們涵蓋了一些主題,如建立框架、標籤、輸入部件、組合框和按鈕。你還建立了一個函式來根據使用者的輸入轉換貨幣。

有幾種方法可以改進這個應用程式。你可以改進使用者介面,使其看起來更有吸引力,增加一個儲存轉換歷史的功能,以及更多。

評論留言