iT邦幫忙

0

py專題暫存

p
import tkinter as tk
import tkinter.font as tkFont
import matplotlib.pyplot as plt
from PIL import Image,ImageTk
import requests
import bs4
import pandas as pd
import csv

def get_url(url):
    response = requests.get(url)
    root = bs4.BeautifulSoup(response.text, "html.parser")
    return root


def get_excel(root):
    data = root.find_all('a', class_="btn")
    for x in data:
        if('Excel' in x.text):
            link = "https://rate.bot.com.tw"+x['href']
    return link


def save_scv(url):
    with requests.Session() as s:
        download = s.get(url)
        decoded_content = download.content.decode('utf-8')
        cr = csv.reader(decoded_content.splitlines(), delimiter=',')
        my_list = list(cr)
        NT=['NTD', '本行買入', '1.00000', '1', '1', '1', '1', '1', '1', '1', '1', '本行賣出', '1', '1', '1', '1', '1', '1', '1', '1', '1', '']
        my_list.append(NT)
        return my_list


def writeList2CSV(myList, filePath):
    df_data = pd.DataFrame(myList)  
    df_data.to_csv(filePath, mode='w', header=True, index=None)

def UpData():
    try:
        url = 'https://rate.bot.com.tw/xrt?Lang=zh-TW'
        file_name="data.csv"
        writeList2CSV(save_scv(get_excel(get_url(url))), file_name)
        print("更新資料完成")
    except:
        print("更新失敗")
##----------------------取得匯率csv--------------------------------------------

def get_data(csv_name):
    data = pd.read_csv(csv_name)
    data = data.values
    dict_rate= {}
    for x in data:
        dict_rate[x[0]] = x[2]
    return dict_rate

def show_ExchangeRate():
    num=-1
    for x in  ExchangeRate:
        num+=1
        if(num==0):
            continue
def get_list():
    list_data_key.clear()
    list_data_value.clear()
    ExchangeRate = get_data('data.csv')
    ##del ExchangeRate['幣別']
    list_key=list(ExchangeRate.keys())
    list_value=list(map(float,ExchangeRate.values()))
    for x in list_value:
            list_data_value.append(x)
    for x in list_key:
            list_data_key.append(x)
    print("已取得資料")        

def cal(now_num,change_num):
    if(now_num<0 or now_num<0 ):
        print("請確認是否選擇兩種幣別")
    else:
        try:
            money=float(input_entry.get())
            global now_rate
            global final
            now_rate="匯率比:"+str(list_data_key[now_num])+str(list_data_value[now_num])+"|"+str(list_data_key[change_num])+str(list_data_value[change_num])
            final=str(money)+str(list_data_key[now_num])+"=>"+str(round(money/New_Data[change_num],3))+str(list_data_key[change_num])
            print(now_rate)
            print(final)
            final_frame = tk.Frame(window).pack(side=tk.TOP)
            final_label= tk.Label(final_frame, text=final,font=fontStyle1).pack()
        except:
            print("錯誤,請檢查是否選擇幣別或輸入值")
        now_num=-1
        change_num=-1
##----------------------讀入csv 轉成list處理 計算--------------------------------------------
        
def show_jpg(name):
    im=Image.open(name)
    img=ImageTk.PhotoImage(im)
    imLabel=tk.Label(window ,image=img)
    imLabel.pack(side = tk.BOTTOM)
    window .mainloop()
def p():
    try:
        color=[]
        for x in range(len(New_Data)):
            if(x==now_num):
                color.append("red")
            else:
                color.append("blue")
        plt.figure(figsize=(10, 5))
        plt.bar(list_data_key, New_Data,color=color)
        print(now_num)
        title="ExchangeRate with "+list_data_key[now_num]
        plt.xlim(0, len(New_Data))
        plt .xticks(fontsize=13)
        plt.ylim(0,max(New_Data)+max(New_Data)/10)
        plt.title(title)
        plt.xlabel('x(Currency)')
        plt.ylabel('y')
        name="./pic.jpg"
        plt.savefig(name)
        plt.show()
        show_jpg(name)
    except:
        print("錯誤2")
##----------------------繪畫--------------------------------------------

def choose1(num,New_Data):
    print("目前貨幣:",list_data_key[num])
    global now_num
    now_num=num
    if(len(New_Data)!=0):
        New_Data.clear()
    for x in range(20):
        New_Data.append(list_data_value[x]/list_data_value[num])

def choose2(num):
    global change_num
    change_num=num
    print("欲轉貨幣:",list_data_key[change_num])

def get_botton1():
    get_list()
    data_frame1 = tk.Frame(window)
    data_frame1.pack()
    data_frame_label= tk.Label(data_frame1, text='選擇目前幣別',font=fontStyle2)
    data_frame_label.pack(side=tk.LEFT)
    num=-1
    for x in list_data_key:
        try:
            num+=1
            data_frame_label= tk.Button(data_frame1, text=str(x),command=lambda num=num :choose1(num,New_Data))
            data_frame_label.pack(side=tk.LEFT)
        except:
            print("錯誤1")
def get_botton2():
    get_list()
    data_frame2 = tk.Frame(window)
    data_frame2.pack()
    data_frame_labe2= tk.Label(data_frame2, text='選擇欲轉幣別',font=fontStyle2).pack(side=tk.LEFT)
    num=-1
    for x in list_data_key:
        try:
            num+=1
            data_frame_labe2= tk.Button(data_frame2, text=str(x),command=lambda num=num :choose2(num))
            data_frame_labe2.pack(side=tk.LEFT)
        except:
            print("錯誤3")    
##----------------------按鈕相關--------------------------------------------


ExchangeRate={}
list_data_key=[]
list_data_value=[]
New_Data=[]
now_num=-1
change_num=-1
now_rate=""
final=""

window = tk.Tk()
imLabel=tk.Label(window)
window.title('匯率計算器')
window.geometry('800x600')
window.configure(background='orange')
fontStyle1 = tkFont.Font(size=20)
fontStyle2 = tkFont.Font(size=10)
header_label = tk.Label(window, text='匯率計算器', font=fontStyle1).pack()

# 更新匯率
UpData_frame = tk.Frame(window).pack(side=tk.TOP)
UpData_label = tk.Button(UpData_frame, text="更新匯率",command=UpData,font=fontStyle2).pack()
#取得資料
#UpData_label = tk.Button(UpData_frame, text="取得轉換資料",command=get_botton2,font=fontStyle2)
#UpData_label.pack()
#圖片
pic_label = tk.Button(UpData_frame, text="顯示圖片",command=p,font=fontStyle2).pack()
#生成按鈕
get_botton1()
get_botton2()
#輸入金額
input_frame = tk.Frame(window)
input_frame.pack(side=tk.TOP)
input_label = tk.Label(input_frame, text='請輸入金額')
input_label .pack(side=tk.LEFT)
input_entry= tk.Entry(input_frame)
input_entry.pack(side=tk.LEFT)
#開始計算
cal_frame=tk.Frame(window).pack(side=tk.LEFT)
cal_label = tk.Button(cal_frame, text="開始計算",command=lambda :cal(now_num,change_num),font=fontStyle2).pack()

result_label = tk.Label(window).pack()
window.mainloop()

尚未有邦友留言

立即登入留言