在本文中,我们将构建一个令人兴奋的项目,您可以通过该项目制作货币转换器。对于用户界面,我们将使用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库。因此,我们需要导入库。
import requestsfrom tkinter import *import tkinter as tkfrom tkinter import ttk
三、创建CurrencyConverter类
现在,我们将创建CurrencyConverter类,该类将获取实时汇率并转换货币并返回转换后的金额。
1、让我们创建class的构造函数
class RealTimeCurrencyConverter(): def __init__(self,url): self.data = requests.get(url).json() self.currencies = self.data['rates']
requests.get(url)将页面加载到我们的python程序中,然后.json()会将页面转换为json文件。我们将其存储在数据变量中。
2、Convert()方法:
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
此方法采用以下参数:
From_currency:需要转换的货币
to _currency: 想要转换成的货币
Amount:需要转换的金额
并返回转换后的金额
例如:
url = 'https://api.exchangerate-api.com/v4/latest/USD'converter = RealTimeCurrencyConverter(url)print(converter.convert('CNY','USD',100))
100人民币=14.7278美元
四、我们为货币转换器创建一个UI
要创建UI,我们将创建一个CurrencyConverterUI类
def __init__(self, converter): tk.Tk.__init__(self) self.title = 'Currency Converter' self.currency_converter = converter
Converter:货币转换器对象,我们将使用该对象转换货币。上面的代码将创建一个框架。
让我们创建转换器
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 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)
首先,我们设置框架并在其中添加一些信息。在这部分代码执行之后,我们的框架看起来如下。
我们为框架中的货币数量和选项创建输入框。这样用户就可以输入金额并在货币之间进行选择。
# 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)
注意:此代码是__init__的一部分
成功执行代码后,我们显示的为这样。
现在,让我们添加CONVERT按钮,该按钮将调用perform函数。
# 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)
Command = self.perform —— 表示单击时将调用perform()
perform()方法:
perform方法将接受用户输入,并将金额转换为所需的货币,并将其显示在convert_amount输入框上。
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))
注意:此函数是App类的一部分。
RestrictNumberOnly()方法:
现在,让我们在输入框中创建一个限制。因此,该用户只能在“金额”字段中输入数字。前面我们已经讨论过,这将通过我们的RrestricNumberOnly方法完成。
def restrictNumberOnly(self, action, string): regex = re.compile(r"[0-9,]*?(.)?[0-9,]*$") result = regex.match(string) return (string == "" or (string.count('.') <= 1 and result is not None))
注意:此函数是APP类的一部分
五、创建主函数
首先,我们将创建转换器。其次,为Converter创建UI
if __name__ == '__main__': url = 'https://api.exchangerate-api.com/v4/latest/USD' converter = RealTimeCurrencyConverter(url) App(converter) mainloop()
在本文中,我们致力于Python项目以构建货币转换器。