「python」12306餘票查詢GUI

軟件示意圖:

「python」12306餘票查詢GUI

# -*- coding:utf-8 -*-
import threading
import requests
import time
from tkinter import *
from tkinter.ttk import *
from tkinter.messagebox import *


class Application_ui(Frame):
# 這個類僅實現界面生成功能,具體事件處理代碼在子類Application中。
def __init__(self, master=None):
Frame.__init__(self, master)
self.master.title('12306查票系統')
self.master.geometry('795x351')
self.createWidgets()

def createWidgets(self):
self.top = self.winfo_toplevel()
self.bum = self.winfo_toplevel()
frame = Frame()

frame.place(x=20, y=60, width=750, height=259)
self.style = Style()

self.style.configure('Label1.TLabel', anchor='w', font=('宋體', 9, 'bold'))
self.Label1 = Label(self.top, text='出發地:', style='Label1.TLabel')
self.Label1.place(relx=0.03, rely=0.068, relwidth=0.072, relheight=0.048)

self.Text1Var = StringVar(value='')
self.Text1 = Entry(self.top, textvariable=self.Text1Var, font=('宋體', 9))
self.Text1.place(relx=0.091, rely=0.046, relwidth=0.142, relheight=0.094)

self.style.configure('Label1.TLabel', anchor='w', font=('宋體', 9, 'bold'))
self.Label1 = Label(self.top, text='目的地:', style='Label1.TLabel')
self.Label1.place(relx=0.262, rely=0.068, relwidth=0.072, relheight=0.048)

self.Text2Var = StringVar(value='')
self.Text2 = Entry(self.top, textvariable=self.Text2Var, font=('宋體', 9))
self.Text2.place(relx=0.322, rely=0.046, relwidth=0.142, relheight=0.094)

self.style.configure('Command1.TButton', font=('宋體', 9, 'bold'))
self.Command1 = Button(self.top, text='查 詢', command=self.Command2, style='Command1.TButton')
self.Command1.place(relx=0.785, rely=0.046, relwidth=0.172, relheight=0.094)


self.style.configure('Label1.TLabel', anchor='w', font=('宋體', 9, 'bold'))
self.Label2 = Label(self.top, text='出發日期:', style='Label2.TLabel')
self.Label2.place(relx=0.493, rely=0.058, relwidth=0.092, relheight=0.048)
self.number = StringVar()
numberChosen = Combobox(self.top, textvariable=self.number)
numberChosen.place(relx=0.574, rely=0.049, relwidth=0.142, relheight=0.074)
numberChosen['values'] = (1, 2, 4, 42, 100) # 設置下拉列表的值
values = []
y = int(time.strftime("%Y", time.localtime()))
m = int(time.strftime("%m", time.localtime()))
d = int(time.strftime("%d", time.localtime()))
i = 0
yy = y
mm = m
dd = d
while i < 30: # 30天數據
if m in (1, 3, 5, 7, 8, 10, 12):
if d + i > 31:
dd = d + i - 31
mm = m + 1
if mm > 12:
yy = y + 1
mm = mm - 12
else:
dd = d + i
elif m in (4, 6, 9, 11):
if d + i > 30:
dd = d + i - 30
mm = m + 1
if mm > 12:
yy = y + 1
mm = mm - 12
else:
dd = d + i
else:
if (m % 400 == 0) or ((m % 4 == 0) and (m % 100 != 0)):
if d + i > 29:
dd = d + i - 29
mm = m + 1
if mm > 12:
yy = y + 1
mm = mm - 12
else:
dd = d + i
else:
if d + i > 28:
dd = d + i - 28
mm = m + 1

if mm > 12:
yy = y + 1
mm = mm - 12
else:
dd = d + i
s = '%d-%02d-%02d' % (yy, mm, dd)
values.append(s)
i += 1
numberChosen['values'] = tuple(values)
numberChosen.current(0) # 設置下拉列表默認顯示的值,0為 numberChosen['values'] 的下標值

scrollBar = Scrollbar(frame)
scrollBar.pack(side=RIGHT, fill=Y)
self.tree = Treeview(frame, height=259,
columns=("車次", "出發站名", "到達站名", "出發時間", "到達時間", "一等座", "二等座", "硬臥", "軟臥", "硬座", "無座"),
show="headings", yscrollcommand=scrollBar.set)
scrollBar.configure(command=self.tree.yview)
self.tree.column('車次', width=50, anchor='center')
self.tree.column('出發站名', width=80, anchor='center')
self.tree.column('到達站名', width=80, anchor='center')
self.tree.column('出發時間', width=80, anchor='center')
self.tree.column('到達時間', width=80, anchor='center')
self.tree.column('一等座', width=60, anchor='center')
self.tree.column('二等座', width=60, anchor='center')
self.tree.column('硬臥', width=60, anchor='center')
self.tree.column('軟臥', width=60, anchor='center')
self.tree.column('硬座', width=60, anchor='center')
self.tree.column('無座', width=60, anchor='center')
self.tree.heading('車次', text='車次')
self.tree.heading('出發站名', text='出發站名')
self.tree.heading('到達站名', text='到達站名')
self.tree.heading('出發時間', text='出發時間')
self.tree.heading('到達時間', text='到達時間')
self.tree.heading('一等座', text='一等座')
self.tree.heading('二等座', text='二等座')
self.tree.heading('硬臥', text='硬臥')
self.tree.heading('軟臥', text='軟臥')

self.tree.heading('硬座', text='硬座')
self.tree.heading('無座', text='無座')
self.tree.pack()


class Application(Application_ui):
# 這個類實現具體的事件處理回調函數。界面生成代碼在Application_ui中。
def __init__(self, master=None):
Application_ui.__init__(self, master)
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
}
# 獲取各個城市的編號
city_url = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9077"
rep = requests.get(city_url, headers=header)
self.areatocode = {}
# 把內容以{城市名:對應的編號}存入字典
for i in rep.content.decode().split("@")[1:]:
if i:
tmp = i.split("|")
self.areatocode[tmp[1]] = tmp[2]

def Command2(self):
"""點擊查詢按鈕觸發的邏輯"""
start1 = self.Text1.get()
to1 = self.Text2.get()
date = self.number.get()
# 這裡日期判斷不夠嚴格 自己可以附加
now_data = time.strftime('%Y.%m.%d', time.localtime(time.time()))
if not start1:
showerror(title='警告', message='出發地不能為空')
elif start1 not in self.areatocode:
showerror(title='警告', message='輸入錯誤,沒有找到該城市')
elif not to1:
showerror(title='警告', message='目的地不能為空')
elif to1 not in self.areatocode:
showerror(title='警告', message='輸入錯誤,沒有找到該城市')

elif not date:
showerror(title='警告', message='輸入錯誤,沒有找到該日期')
elif int(date.replace('-', '')) < int(now_data.replace('.', '')):
showerror(title='警告', message='日期不能小於當期日期')
elif start1 and to1 and date:
if self.Command1['text'] == '查 詢':
self.Command1['text'] = '正 在 查 詢'
# 每次點擊查詢按鈕後將按鈕設置為不可用 防止多次發送請求
self.Command1.config(state=DISABLED)
# 啟動一個線程防止程序在查詢期間被卡主 出現未響應的情況
t = threading.Thread(target=self.Command1_Cmd, args=(start1, to1, date))
t.start()

def Command1_Cmd(self, start1, to1, date):
try:
start = self.areatocode[start1]
to = self.areatocode[to1]
# 這裡有學生和成人之分 默認直接寫成成人了
student = "ADULT"
url = "https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date=" + date + "&leftTicketDTO.from_station=" + start + "&leftTicketDTO.to_station=" + to + "&purpose_codes=" + student
rep = requests.get(url, headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"})
patrst01 = '"result":\[(.*?)\]'
# 正則提取查票的結果
rst0 = re.compile(patrst01).findall(rep.content.decode())
checimap_pat = '"map":({.*?})'
checimap = eval(re.compile(checimap_pat).findall(rep.content.decode())[0])
if rst0[0] == '':
showinfo(title='警告', message='沒有找到該車次的信息')
rst01 = rst0[0]
allcheci = rst01.split(",")
# 點擊查詢按鈕 先把內容清空
x = self.tree.get_children()
for item in x:
self.tree.delete(item)

for i in range(0, len(allcheci)):

thischeci = allcheci[i].split("|")
code = thischeci[3]
fromname = thischeci[6]
fromname = checimap[fromname]
# [7]---toname
toname = thischeci[7]
toname = checimap[toname]
# [8]---stime
stime = thischeci[8]
# [9]---atime
atime = thischeci[9]
# [28]---一等座
yz = thischeci[31] if str(thischeci[31]) != '' else "-"
# [29]---二等座
wz = thischeci[30] if str(thischeci[30]) != '' else "-"
# [30]---硬座
ze = thischeci[29] if str(thischeci[29]) != '' else "-"
# [31]---無座
zy = thischeci[26] if str(thischeci[26]) != '' else "-"
# 硬臥
xx = thischeci[28] if str(thischeci[28]) != '' else "-"
# 軟臥
yy = thischeci[23] if str(thischeci[23]) != '' else "-"
# 將數據回顯到軟件中
self.tree.insert('', i, values=(
code, fromname, toname, stime, atime, str(yz), str(wz), str(xx), str(yy), str(ze), str(zy)))
# 查詢完畢將按鈕變為正常
self.Command1.config(state=NORMAL)
self.Command1['text'] = '查 詢'
except:
self.Command1.config(state=NORMAL)
self.Command1['text'] = '查 詢'


if __name__ == "__main__":
top = Tk()
top.resizable(width=False, height=False)
Application(top).mainloop()
try:
top.destroy()
except:
pass


分享到:


相關文章: