我正在制作一個小型專案貨幣轉換器。當我將美元轉換為任何其他貨幣時,它會正確顯示正確答案。如果我選擇美元以外的其他貨幣,結果與我輸入的數字/金額相同。但我想將輸入的貨幣轉換為 to_currency。我該如何解決?
# Import the modules needed
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import requests
url = 'https://v6.exchangerate-api.com/v6/8a0fcd7df32ea4704f4fc48d/latest/USD'
response = requests.get(url)
response.raise_for_status()
data = response.json()
currency_key = data['conversion_rates']
def convert():
input_02.delete(0, END)
amount = input_01.get()
if amount == "":
messagebox.showinfo(title="Invalid", message="Please Insert the Amount")
return False
currency_02 = to_currency.get()
for i, j in currency_key.items():
var01 = i.upper()
var02 = currency_02.upper()
if var01 in var02:
try:
if from_currency.get() != 'USD':
amount = float(amount)/j
value = amount*j
input_02.insert(0, f"{value}")
else:
value = j*float(amount)
value = round(value, 4)
input_02.insert(0, f"{value}")
except ValueError:
messagebox.showinfo(title="Invalid", message="Please insert Amount in Digits")
window = Tk()
window.title('Currency Converter!')
window.iconbitmap('currency.ico')
window.config(padx=50, bg='#0CA7D3')
label_01 = Label(text="Currency Converter GUI", bg='#0CA7D3', foreground='white', font=("arial", 20, "bold"))
label_01.grid(column=0, row=0, columnspan=3, pady=15)
from_currency = StringVar()
from_currency.set(" USD ")
dropdown_01 = ttk.Combobox(textvariable=from_currency, width=16, font=("arial", 10, "bold"), state='enable',
values=list(currency_key))
dropdown_01.grid(column=0, row=1)
input_01 = Entry(font=("arial", 10, "bold"), width=19)
input_01.focus()
input_01.grid(column=0, row=2, pady=5)
to_currency = StringVar()
to_currency.set(" PKR ")
dropdown_02 = ttk.Combobox(textvariable=to_currency, width=16, font=("arial", 10, "bold"), state='readonly',
values=list(currency_key))
dropdown_02.grid(column=2, row=1)
input_02 = Entry(font=("arial", 10, "bold"), width=19)
input_02.grid(column=2, row=2, pady=5)
button = Button(text="Convert", command=convert, width=8, bg='#0084AB', fg='white', font=("arial", 10, "bold"))
button.grid(column=0, row=3, pady=20)
window.mainloop()
uj5u.com熱心網友回復:
我沒有嘗試運行代碼,但看看這個:
amount = float(amount)/j
value = amount*j
input_02.insert(0, f"{value}")
你是乘除amount以j,所以 finalvalue等于 initial amount。
作為旁注,我會嘗試使用更具描述性的變數名稱。
uj5u.com熱心網友回復:
from_currencyto的比率to_currency可以通過以下方式計算:
rate = currency_key[to_currency.get()] / currency_key[from_currency.get()]
以下是修改后的convert():
def convert():
amount = input_01.get().strip()
if amount == "":
messagebox.showinfo(title="Invalid", message="Please insert the amount")
return False
try:
rate = currency_key[to_currency.get()] / currency_key[from_currency.get()]
value = float(amount) * rate
input_02.delete(0, "end")
input_02.insert("end", value)
except ValueError:
messagebox.showinfo(title="Invalid", message="Please insert amount in digits")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/505392.html
下一篇:將小部件與包對齊
