实现一个简单的火车票查询工具,用户可以通过图形界面输入出发站、目的地站和日期,然后点击“查询”按钮来获取相关的火车票信息。程序会调用一个虚构的API接口来获取数据,并在界面上显示查询结果。
主要用到的技术包括:
- Python: 整个应用程序是用Python编写的。
- Tkinter: 用于创建图形用户界面(GUI),允许用户与应用程序进行交互。
- Requests库: 用于发送HTTP请求以从API获取数据。
- 异常处理: 在请求过程中使用了try-except块来捕获和处理可能发生的网络请求异常。
以下是完整的artifact代码:
import tkinter as tk
from tkinter import messagebox
import requests
def query_train_tickets(from_station, to_station, date):
# 这里使用的是一个虚构的API地址,请替换为实际可用的API地址
api_url = f"https://api.example.com/train_tickets?from={from_station}&to={to_station}&date={date}"
try:
response = requests.get(api_url)
response.raise_for_status()
tickets_info = response.json()
if not tickets_info['data']:
return "没有找到相关车次信息"
result = ""
for ticket in tickets_info['data']:
train_no = ticket.get('train_no', '未知')
departure_time = ticket.get('departure_time', '未知')
arrival_time = ticket.get('arrival_time', '未知')
duration = ticket.get('duration', '未知')
price = ticket.get('price', '未知')
result += f"车次: {train_no}, 出发时间: {departure_time}, 到达时间: {arrival_time}, 历时: {duration}, 价格: {price}\n"
return result
except requests.exceptions.RequestException as e:
return f"请求出错: {e}"
def on_query():
from_station = entry_from.get().strip()
to_station = entry_to.get().strip()
date = entry_date.get().strip()
if not from_station or not to_station or not date:
messagebox.showwarning("输入错误", "请填写所有字段")
return
result = query_train_tickets(from_station, to_station, date)
text_result.delete(1.0, tk.END)
text_result.insert(tk.END, result)
# 创建主窗口
root = tk.Tk()
root.title("火车票查询工具")
# 设置窗口大小
root.geometry("500x400")
# 创建标签和输入框
label_from = tk.Label(root, text="出发站:")
label_from.pack(pady=5)
entry_from = tk.Entry(root, width=30)
entry_from.pack(pady=5)
label_to = tk.Label(root, text="目的地站:")
label_to.pack(pady=5)
entry_to = tk.Entry(root, width=30)
entry_to.pack(pady=5)
label_date = tk.Label(root, text="日期 (YYYY-MM-DD):")
label_date.pack(pady=5)
entry_date = tk.Entry(root, width=30)
entry_date.pack(pady=5)
# 创建查询按钮
button_query = tk.Button(root, text="查询", command=on_query)
button_query.pack(pady=20)
# 创建结果显示区域
text_result = tk.Text(root, height=10, width=60)
text_result.pack(pady=10)
# 运行主循环
root.mainloop()
请注意,api_url
中使用的 API 地址是一个虚构的示例,请替换为实际可用的 API 地址才能正常使用该工具。
效果展示