用python的tkinter和爬虫制作一个天气查询窗口

 翻开从前的代码,发现有段时间对 tkinter 图形化开发界面特别感兴趣,所以在这里和大家分享一下,做的一个小小的实例。

那么如何快速的创建一个GUI程序,只需要先导入Tkinter模块,创建一个窗口对象,在进行消息的循环,这样就创建成功了。

from Tkinter import *
root = Tk()
root.mainloop()

用python的tkinter和爬虫制作一个天气查询窗口_第1张图片

在中间填写的部分便是tkinter的组件部分,可以在这上面进行学习:https://www.runoob.com/python/python-gui-tkinter.html

话不多说,先呈上代码。 

from tkinter import *
import requests
import json
import random

HEIGHT = 700
WIDTH = 800

def format_response(data):
    try:
        city = data['result']['city']
        date = data['result']['date']
        week = data['result']['week']
        weather = data['result']['weather']
        temp = data['result']['templow']
        temphigh = data['result']['temphigh']
        final_str = 'city: %s \n date: %s \n week: %s \n weather: %s \n temp: %s  temphigh: %s' %(city,date,week,weather,temp,temphigh)
    except:
        final_str = 'there was a problem retrieving that information !!!'


    return final_str


def get_weather():
    
    cityname = entry.get()
    url = "https://api.jisuapi.com/weather/query?appkey=e5de5fcbe1800420&city="+str(cityname)
    data = requests.get(url).text
    data = json.loads(data)
    
    label['text'] = format_response(data)

root = Tk()
root.title('hello')


canvas = Canvas(root,height=HEIGHT,width=WIDTH)
canvas.pack()

images = ['test4.png','test5.png','test6.png']
background_image = PhotoImage(file=random.choice(images))
background_label = Label(root,image=background_image)
background_label.place(relwidth=1,relheight=1)


frame = Frame(root,bg='#80c1ff', bd=5)
frame.place(relx=0.5,rely=0.1,relwidth=0.75,relheight=0.1,anchor='n')

button = Button(frame,text='GET WEATHER',font=40,command=get_weather)
button.place(relx=0.7,relwidth=0.3,relheight=1)



entry = Entry(frame,font=40)
entry.place(relwidth=0.65,relheight=1)

lower_frame = Frame(root,bg='#80c1ff', bd=10)
lower_frame.place(relx=0.5,rely=0.25,relwidth=0.75,relheight=0.6,anchor='n')

label = Label(lower_frame,text="this is a label",font=('华文行楷',20),bg ='white')
label.place(relwidth=1,relheight=1)

root.mainloop()

实现图:

用python的tkinter和爬虫制作一个天气查询窗口_第2张图片

背景的图片可以随机改变,在images中放入图片的路径即可,这样就可以打造一个专属的查询天气的小工具了。

see you again !!! 

你可能感兴趣的:(python随笔)