界面设计
python的界面设计主要用tkinter库来进行,而且无需新下载,在python安装时就已经包含了tkinter库。
import tkinter as tk
from tkinter import ttk #ttk中包含选项框Combobox
简易的实时汇率计算器仅需要2个选项控件(Combobox)、1个输入控件(Enter)、1个文本控件(Text)、1个按钮控件(Button)。各个控件的操作可以参考该博客:Tkinter python3
实现代码如下:
win=tk.Tk() #建立界面
win.title('exchange Rate') #设置应用名称
win.geometry('400x400+200+0') #界面大小
#创建选项控件
preChangeBox=ttk.Combobox(win,textvariable=var1,font=15)
#选项名称
preChangeBox["values"]=("美金","人民币","英镑","欧元","日元")
'''控件位置,前两个表示控件相对于整个界面的大小,后两
个表示控制相对于整个界面的位置,在整个界面变化时随之变化。'''
preChangeBox.place(relwidth=0.20,relheight=0.06,relx=0.15,rely=0.25)
#将控件显示在界面上
preChangeBox.pack()
#同理创建另外一个选项控件
afChangeBox=ttk.Combobox(win,textvariable=var2,font=15)
afChangeBox.place(relwidth=0.20,relheight=0.06,relx=0.15,rely=0.45)
afChangeBox["value"]=("美金","人民币","英镑","欧元","日元")
#afChangeBox.pack()
#建立输入控件
ent1=tk.Entry(win,font=15)
ent1.place(relwidth=0.30,relheight=0.06,relx=0.55,rely=0.25)
#创建文本控件
ent2=tk.Text(win, font=15)
ent2.place(relwidth=0.30,relheight=0.06,relx=0.55,rely=0.45)
#创建按钮控件
#Button中的activebackground和activeforeground表示控件在按下前后的颜色
but1=tk.Button(win,text='转换',font=('arial',14),activebackground='white',activeforeground='grey',command=currencyExchange)
but1.place(relwidth=0.3,relheight=0.08,relx=0.35,rely=0.65)
#进入消息循环,程序运行起来
win.mainloop()
联网获取数据
以我的程序为例,我在网上找到了免费的货币汇率接口,每两分钟更新一次。通过接口获取信息需要json和urllib两个库,同样不需要另行下载,python原生库中包含这两个库。
import json
import urllib
from urllib import parse,request
我们需要通过request中的urlopen函数来打开相应的网站,并用json中的load函数来提取和提纯数据,代码如下:
def request1(m="GET"): #m="Get"表示请求方式
appkey="*********************************" #请求参数
url="******************************" #请求地址
params={"key":appkey,"type":""}
params=parse.urlencode(params)
if m=="GET": #如果是以GET方式请求
f=request.urlopen("%s?%s"%(url,params)) #打开网站
else:
f=urllib.urlopen(url,params)
content=f.read()
res=json.loads(content) #提取数据
打印res可以得到一下数据:
{'error_code': 0, 'resultcode': '200', 'reason': 'SUCCESSED!', 'result'