正題: python 調用三方API實現實時查詢油價查詢窗口(GUI)

1.導入模塊:

import tkinter as tk
from tkinter import ttk
import requests
from datetime import datetime

2.定義獲取油價函數:

def fetch_oil_price():
selected_province = province_var.get()
uid = ''
appkey = ''
url = 'http://oil.ylapi.cn/todayoil/info.u'
params = {
'uid': uid,
'appkey': appkey,
'prov': selected_province
}
response = requests.post(url, data=params)
print(response.text) # 打印響應內容

data = response.json()
if 'code' in data:
if data['code'] == '1000':
oil_prices = data['data']
update_time_str = oil_prices['ct']
update_time = datetime.strptime(update_time_str, '%Y-%m-%d %H:%M:%S.%f')
update_time_formatted = update_time.strftime('%Y-%m-%d')

update_time_label.config(text=f"數據更新時間:{update_time_formatted}")

for widget in oil_price_frame.winfo_children():
widget.destroy()

ttk.Label(oil_price_frame, text="類型").grid(row=0, column=0)
ttk.Label(oil_price_frame, text="油價(元/升)").grid(row=0, column=1)

row_num = 1
for key, value in oil_prices.items():
if key.startswith('p'):
type_name = key.replace('p', '') + "號" + ("柴油" if key == 'p0' else "汽油")
ttk.Label(oil_price_frame, text=type_name).grid(row=row_num, column=0)
ttk.Label(oil_price_frame, text=value).grid(row=row_num, column=1)
row_num += 1
else:
error_label.config(text=f"獲取油價失敗:{data['msg']}")
else:
error_label.config(text="獲取油價失敗:未收到有效的響應。")

3.創建主窗口和框架:

root = tk.Tk()
root.title("今日油價查詢")

main_frame = ttk.Frame(root)
main_frame.pack(padx=20, pady=20)

4.創建省份選擇組合框和查詢按鈕:

province_label = ttk.Label(main_frame, text="選擇省份:")
province_label.grid(row=0, column=0, padx=10, pady=10)

provinces = [
"北京", "天津", "河北", "山西", "內蒙古", "遼寧", "吉林", "黑龍江",
"上海", "江蘇", "浙江", "安徽", "福建", "江西", "山東", "河南",
"湖北", "湖南", "廣東", "廣西", "海南", "重慶", "四川", "貴州",
"云南", "西藏", "陜西", "甘肅", "青海", "寧夏", "新疆", "臺灣",
"香港", "澳門"
]
province_var = tk.StringVar()
province_combobox = ttk.Combobox(main_frame, textvariable=province_var, values=provinces)
province_combobox.grid(row=0, column=1, padx=10, pady=10)
province_combobox.current(0)

fetch_button = ttk.Button(main_frame, text="查詢", command=fetch_oil_price)
fetch_button.grid(row=0, column=2, padx=10, pady=10)

5.創建數據顯示標簽和錯誤消息標簽:

update_time_label = ttk.Label(main_frame, text="")
update_time_label.grid(row=1, column=0, columnspan=3)

oil_price_frame = ttk.Frame(main_frame)
oil_price_frame.grid(row=2, column=0, columnspan=3, padx=10, pady=10)

error_label = ttk.Label(main_frame, text="")
error_label.grid(row=3, column=0, columnspan=3)

6.運行主事件循環:

root.mainloop()

7.完整代碼:

import tkinter as tk
from tkinter import ttk
import requests
from datetime import datetime

def fetch_oil_price():
selected_province = province_var.get()
uid = ''
appkey = ''
url = 'http://oil.ylapi.cn/todayoil/info.u'
params = {
'uid': uid,
'appkey': appkey,
'prov': selected_province
}
response = requests.post(url, data=params)
print(response.text) # 打印響應內容

data = response.json()
if 'code' in data:
if data['code'] == '1000':
oil_prices = data['data']
update_time_str = oil_prices['ct']
update_time = datetime.strptime(update_time_str, '%Y-%m-%d %H:%M:%S.%f')
update_time_formatted = update_time.strftime('%Y-%m-%d')

update_time_label.config(text=f"數據更新時間:{update_time_formatted}")

for widget in oil_price_frame.winfo_children():
widget.destroy()

ttk.Label(oil_price_frame, text="類型").grid(row=0, column=0)
ttk.Label(oil_price_frame, text="油價(元/升)").grid(row=0, column=1)

row_num = 1
for key, value in oil_prices.items():
if key.startswith('p'):
type_name = key.replace('p', '') + "號" + ("柴油" if key == 'p0' else "汽油")
ttk.Label(oil_price_frame, text=type_name).grid(row=row_num, column=0)
ttk.Label(oil_price_frame, text=value).grid(row=row_num, column=1)
row_num += 1
else:
error_label.config(text=f"獲取油價失敗:{data['msg']}")
else:
error_label.config(text="獲取油價失敗:未收到有效的響應。")

root = tk.Tk()
root.title("今日油價查詢")

main_frame = ttk.Frame(root)
main_frame.pack(padx=20, pady=20)

province_label = ttk.Label(main_frame, text="選擇省份:")
province_label.grid(row=0, column=0, padx=10, pady=10)

provinces = [
"北京", "天津", "河北", "山西", "內蒙古", "遼寧", "吉林", "黑龍江",
"上海", "江蘇", "浙江", "安徽", "福建", "江西", "山東", "河南",
"湖北", "湖南", "廣東", "廣西", "海南", "重慶", "四川", "貴州",
"云南", "西藏", "陜西", "甘肅", "青海", "寧夏", "新疆", "臺灣",
"香港", "澳門"
]
province_var = tk.StringVar()
province_combobox = ttk.Combobox(main_frame, textvariable=province_var, values=provinces)
province_combobox.grid(row=0, column=1, padx=10, pady=10)
province_combobox.current(0)

fetch_button = ttk.Button(main_frame, text="查詢", command=fetch_oil_price)
fetch_button.grid(row=0, column=2, padx=10, pady=10)

update_time_label = ttk.Label(main_frame, text="")
update_time_label.grid(row=1, column=0, columnspan=3)

oil_price_frame = ttk.Frame(main_frame)
oil_price_frame.grid(row=2, column=0, columnspan=3, padx=10, pady=10)

error_label = ttk.Label(main_frame, text="")
error_label.grid(row=3, column=0, columnspan=3)

root.mainloop()

最后可以使用?pip3 install pyinstaller?打包成exe格式.

使用 Oilprice API 和 Python,我們可以輕松地獲取實時和歷史油價數據。這些數據對于金融分析師、投資者以及其他需要實時油價信息的人士來說是非常寶貴的資源。通過簡單的腳本,你可以快速整合這些數據到你的項目中。

上一篇:

如何在Python、PHP和Ruby中調用DNS查詢API接口

下一篇:

FILES 文件托管平臺 API 使用教程及解決方案
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費