from tkinter import *
import requests
LOG_LINE_NUM = 0
class MY_GUI():
def __init__(self, init_window_name):
self.init_window_name = init_window_name
# 设置窗口
def set_init_window(self):
self.init_window_name.title("天气预报demo") # 窗口名
self.init_window_name.geometry(‘800x500+200+50‘)
# 标签
self.init_data_label = Label(self.init_window_name, text="输入城市名")
self.init_data_label.grid(row=0, column=0)
self.result_data_label = Label(self.init_window_name, text="天气预测结果")
self.result_data_label.grid(row=0, column=12)
# 文本框
self.init_data_Text = Text(self.init_window_name, width=20, height=1) # 城市名录入框
self.init_data_Text.grid(row=1, column=0, rowspan=2, columnspan=5)
self.result_data_Text = Text(self.init_window_name, width=70, height=30) # 处理结果展示
self.result_data_Text.grid(row=1, column=12, rowspan=10, columnspan=10)
# 按钮
self.str_trans_to_md5_button = Button(self.init_window_name, text="获取天气情况", bg="lightblue", width=10,
command=self.str_trans_to_md5) # 调用内部方法 加()为直接调用
self.str_trans_to_md5_button.grid(row=1, column=11)
# 功能函数
def str_trans_to_md5(self):
city = {‘北京‘: ‘101010100‘,
‘济南‘: ‘101120101‘,
‘青岛‘: ‘101120201‘,
‘武汉‘: ‘101200101‘}
cityname = self.init_data_Text.get(1.0, END).strip()
print(cityname)
citycode = city[cityname]
url = ‘http://wthrcdn.etouch.cn/weather_mini?citykey=%s‘ % citycode
# print(‘城市:{},编号:{}‘.format(cityname,citycode))
# print(url)
res = requests.get(url)
info = res.json()
# print(info)
data = info[‘data‘]
weatherItems = data[‘forecast‘]
today = weatherItems[0]
city = f"【城市:{data[‘city‘]}】\n"
date = f"日期:{today[‘date‘]}\n"
now = f"实时温度:{data[‘wendu‘]}度\n"
tips = f"今日贴士:{data[‘ganmao‘]}\n"
content_today = city + date + now + tips
print(content_today)
self.result_data_Text.delete(1.0, END)
self.result_data_Text.insert(1.0, content_today)
self.result_data_Text.insert(5.0, ‘\n【未来4日天气情况:】\n‘)
forecastItems = ""
for today in weatherItems[1:]:
date = f"日期:{today[‘date‘]}"
temperature = f"温度:{today[‘high‘]} {today[‘low‘]}"
weatherType = f"天气:{today[‘type‘]}"
print(‘{}, {}, {}\n‘.format(date, weatherType, temperature))
content_four_days = date + weatherType + temperature + ‘\n‘
print(content_four_days)
print(type(content_four_days))
forecastItems += content_four_days
self.result_data_Text.insert(8.0, forecastItems)
def gui_start():
init_window = Tk() # 实例化出一个父窗口
ZMJ_PORTAL = MY_GUI(init_window)
ZMJ_PORTAL.set_init_window() # 设置根窗口默认属性
init_window.mainloop() # 父窗口进入事件循环,可以理解为保持窗口运行,否则界面不展示
gui_start()
原文:https://www.cnblogs.com/zhuhukang/p/14810331.html