如何修改Python货币转换APP,使其仅显示转换日期与结果?
实现仅显示转换日期和结果的修改方案
要实现只展示API返回的date和result字段,你需要对API响应进行JSON解析,提取目标字段后格式化显示文本,同时优化标签的创建逻辑避免重复生成控件。
修改后的完整代码
import requests from tkinter import * root = Tk() root.title("Currency Converter") root.geometry("500x460") # 提前初始化结果标签,避免每次点击重复创建 result_label = Label(root, text="") result_label.grid(row=0, column=1, columnspan=2) def currency_convertion(): url = f"https://api.apilayer.com/exchangerates_data/convert?to={to_currency_entry.get()}&from={from_currency_entry.get()}&amount={amount_entry.get()}" payload = {} headers= { "apikey": "" # 请填入你的API密钥 } response = requests.request("GET", url, headers=headers, data=payload) # 解析JSON格式的响应内容 if response.status_code == 200: data = response.json() # 提取日期和结果,添加默认值处理异常情况 conversion_date = data.get("date", "无法获取日期") conversion_result = data.get("result", "无法获取结果") # 格式化要显示的文本,结果保留两位小数 display_text = f"转换日期:{conversion_date}\n转换结果:{conversion_result:.2f}" else: display_text = f"请求失败,状态码:{response.status_code}" # 更新标签内容 result_label.config(text=display_text) from_currency_label = Label(root, text='From Currency') from_currency_label.grid(row=1, column=0, pady=10) to_currency_label = Label(root, text='To Currency') to_currency_label.grid(row=2, column=0, pady=10) amount_label = Label(root, text='Amount') amount_label.grid(row=3, column=0, pady=10) from_currency_entry = Entry(root,) from_currency_entry.grid(row=1, column=1, stick=W+E+N+S, pady=10) to_currency_entry = Entry(root,) to_currency_entry.grid(row=2, column=1, stick=W+E+N+S,pady=10) amount_entry = Entry(root,) amount_entry.grid(row=3, column=1, stick=W+E+N+S, pady=10) button = Button(root, text="Convert", command=currency_convertion) button.grid(row=4, column=1, stick=W+E+N+S) root.mainloop()
关键修改点说明
- JSON解析响应:使用
response.json()将API返回的字符串转换为Python字典,方便直接提取指定字段。 - 提取目标字段:用
data.get(key, 默认值)的方式获取date和result,避免因API返回结构变化或字段缺失导致程序报错。 - 格式化显示文本:通过f-string拼接成易读的格式,对
result保留两位小数,提升数值的可读性。 - 优化标签逻辑:提前在函数外创建
result_label,每次点击按钮时通过config(text=...)更新内容,避免重复生成标签控件造成界面冗余。 - 异常处理:增加状态码判断,当请求失败时显示错误信息,提升用户体验。
内容的提问来源于stack exchange,提问作者Loh Boon How
相关产品推荐
相关产品推荐

