在本文中,我們將構建一個令人興奮的項目,您可以通過該項目製作貨幣轉換器。對於用戶界面,我們將使用tkinter庫。
Python中的貨幣轉換器
- tkinter – 用於用戶界面(UI)
- requests – 獲取網址
貨幣轉換器的python構建步驟
- 實時匯率
- 導入所需的庫
- CurrencyConverter類
- 貨幣轉換器的用戶界面
- 主函數
一、實時匯率
要獲取實時匯率,我們將使用:https://api.exchangerate-api.com/v4/latest/USD
Base – USD:這意味著我們有基準貨幣美元。這意味著要轉換任何貨幣,我們必須先將其轉換為USD,然後再由USD轉換為任意貨幣。
Date and time:顯示上次更新的日期和時間。
Rates:這是基礎貨幣與美元的貨幣匯率。
二、導入我們需要的庫
我們使用tkinter和request庫。因此,我們需要導入庫。
<code>import requests from tkinter import * import tkinter as tk from tkinter import ttk/<code>
三、創建CurrencyConverter類
現在,我們將創建CurrencyConverter類,該類將獲取實時匯率並轉換貨幣並返回轉換後的金額。
1、讓我們創建class的構造函數
<code>class RealTimeCurrencyConverter(): def __init__(self,url): self.data = requests.get(url).json() self.currencies = self.data['rates']/<code>
requests.get(url)將頁面加載到我們的python程序中,然後.json()會將頁面轉換為json文件。我們將其存儲在數據變量中。
2、Convert()方法:
<code> def convert(self, from_currency, to_currency, amount): initial_amount = amount if from_currency != 'USD' : amount = amount / self.currencies[from_currency] # limiting the precision to 4 decimal places amount = round(amount * self.currencies[to_currency], 4) return amount/<code>
此方法採用以下參數:
From_currency:需要轉換的貨幣
to _currency: 想要轉換成的貨幣
Amount:需要轉換的金額
並返回轉換後的金額
例如:
<code>url = 'https://api.exchangerate-api.com/v4/latest/USD' converter = RealTimeCurrencyConverter(url) print(converter.convert('CNY','USD',100))/<code>
四、我們為貨幣轉換器創建一個UI
要創建UI,我們將創建一個CurrencyConverterUI類
<code>def __init__(self, converter): tk.Tk.__init__(self) self.title = 'Currency Converter' self.currency_converter = converter/<code>
Converter:貨幣轉換器對象,我們將使用該對象轉換貨幣。上面的代碼將創建一個框架。
讓我們創建轉換器
<code> self.geometry("500x200") # Label self.intro_label = Label(self, text = 'Welcome to Real Time Currency Convertor', fg = 'blue', relief = tk.RAISED, borderwidth = 3) self.intro_label.config(font = ('Courier',15,'bold')) self.date_label = Label(self, text = f"1 CNY = {self.currency_converter.convert('CNY','USD',1)} USD \n Date : {self.currency_converter.data['date']}", relief = tk.GROOVE, borderwidth = 5) self.intro_label.place(x = 10 , y = 5) self.date_label.place(x = 160, y= 50)/<code>
首先,我們設置框架並在其中添加一些信息。在這部分代碼執行之後,我們的框架看起來如下。
我們為框架中的貨幣數量和選項創建輸入框。這樣用戶就可以輸入金額並在貨幣之間進行選擇。
<code> # Entry box valid = (self.register(self.restrictNumberOnly), '%d', '%P') self.amount_field = Entry(self,bd = 3, relief = tk.RIDGE, justify = tk.CENTER,validate='key', validatecommand=valid) self.converted_amount_field_label = Label(self, text = '', fg = 'black', bg = 'white', relief = tk.RIDGE, justify = tk.CENTER, width = 17, borderwidth = 3) # dropdown self.from_currency_variable = StringVar(self) self.from_currency_variable.set("CNY") # default value self.to_currency_variable = StringVar(self) self.to_currency_variable.set("USD") # default value font = ("Courier", 12, "bold") self.option_add('*TCombobox*Listbox.font', font) self.from_currency_dropdown = ttk.Combobox(self, textvariable=self.from_currency_variable,values=list(self.currency_converter.currencies.keys()), font = font, state = 'readonly', width = 12, justify = tk.CENTER) self.to_currency_dropdown = ttk.Combobox(self, textvariable=self.to_currency_variable,values=list(self.currency_converter.currencies.keys()), font = font, state = 'readonly', width = 12, justify = tk.CENTER) # placing self.from_currency_dropdown.place(x = 30, y= 120) self.amount_field.place(x = 36, y = 150) self.to_currency_dropdown.place(x = 340, y= 120) #self.converted_amount_field.place(x = 346, y = 150) self.converted_amount_field_label.place(x = 346, y = 150)/<code>
注意:此代碼是__init__的一部分
成功執行代碼後,我們顯示的為這樣。
現在,讓我們添加CONVERT 按鈕,該按鈕將調用perform函數。
<code># Convert button self.convert_button = Button(self, text = "Convert", fg = "black", command = self.perform) self.convert_button.config(font=('Courier', 10, 'bold')) self.convert_button.place(x = 225, y = 135)/<code>
Command = self.perform —— 表示單擊時將調用perform()
perform()方法:
perform方法將接受用戶輸入,並將金額轉換為所需的貨幣,並將其顯示在convert_amount輸入框上。
<code>def perform(self): amount = float(self.amount_field.get()) from_curr = self.from_currency_variable.get() to_curr = self.to_currency_variable.get() converted_amount = self.currency_converter.convert(from_curr,to_curr,amount) converted_amount = round(converted_amount, 2) self.converted_amount_field_label.config(text = str(converted_amount))/<code>
注意:此函數是App類的一部分。
RestrictNumberOnly()方法:
現在,讓我們在輸入框中創建一個限制。因此,該用戶只能在“金額”字段中輸入數字。前面我們已經討論過,這將通過我們的RrestricNumberOnly方法完成。
<code>def restrictNumberOnly(self, action, string): regex = re.compile(r"[0-9,]*?(\.)?[0-9,]*#34;) result = regex.match(string) return (string == "" or (string.count('.') <= 1 and result is not None))/<code>
注意:此函數是APP類的一部分
五、創建主函數
首先,我們將創建轉換器。其次,為Converter創建UI
<code>if __name__ == '__main__': url = 'https://api.exchangerate-api.com/v4/latest/USD' converter = RealTimeCurrencyConverter(url) App(converter) mainloop()/<code>
在本文中,我們致力於Python項目以構建貨幣轉換器。