import tkinter
import requests
import json
from tkinter import *
class FindLocation(object):
def __init__(self):
# 创建主窗口,用于容纳其它组件
self.root = tkinter.Tk()
# 给主窗口设置标题内容
self.root.title("天气预报查询")
# 创建一个输入框,并设置尺寸
self.city_input = tkinter.Entry(self.root,width=50)
self.city_input.grid(row=0,column=0)
# 创建一个查询结果的按钮
self.result_button = tkinter.Button(self.root, command = self.find_position, text = "查询",bg='black',fg='white')
self.result_button.grid(row=0,column=1)
#清除按钮
self.clear = tkinter.Button(self.root,text="清除",command=self.inputclear,bg='black',fg='white')
self.clear.grid(row=0,column=2)
# 创建一个回显列表
self.display_info = tkinter.Listbox(self.root, width=50)
self.display_info.grid(row=1)
self.root.mainloop()
def inputclear(self):
self.city_input.delete(0,END)
def gui_arrang(self):
"此方法暂时不用,和界面布局冲突"
self.cityLabel.pack()
self.city_input.pack()
self.result_button.pack()
self.display_info.pack()
self.clear.pack()
def find_position(self):
self.city = self.city_input.get()
url = 'http://www.sojson.com/open/api/weather/json.shtml?city='+self.city
headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0","Accept-Language":"zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3"}
r = requests.get(url,headers = headers)
json = r.json()
try:
date=json["date"] #今日日期
ganmao=json["data"]["ganmao"] #防感冒建议
high=json["data"]["forecast"][0]["high"] #最高温度
low=json["data"]["forecast"][0]["low"] #最低温度
types=json["data"]["forecast"][0]["type"] #天气类型
notice=json["data"]["forecast"][0]["notice"] #注意事项
the_weather_info = ["日期:"+str(date),"生活建议:"+str(ganmao),str(high),str(low), "天气类型:"+str(types), "注意事项:"+str(notice)]
except:
the_weather_info = ["如果您输入的城市无误,请稍后刷新!"]
#清空回显列表可见部分,类似clear命令
for item in range(10):
self.display_info.insert(0,"")
# 为回显列表赋值
for item in the_weather_info:
self.display_info.insert(0,item)
# 这里的返回值,没啥用,就是为了好看
#return the_weather_info
def main():
# 初始化对象
FL = FindLocation()
#FL.gui_arrang()
# 主程序执行
#FL.mainloop()
pass
if __name__ == "__main__":
main()