Python--weather.NO.1---了解tkinter和requests的基本用法

 1.目标:

 初步认识tkinter or requests

2.准备:(https://pasteme.cn/28686

2.1参考资料《用的时候再看也可以》

视频资料(全英、无字幕、慎选) 、略(英文版)、 tkinter详解中文版

廖雪峰requests详解

(再几个与爬虫原理相关的视频,毕竟每个人实操不一样,需要自己调整)

 

2.2需求:  注册Gmail 或者Msn..... 

一些坑:

②注册gmail:通过qq邮箱那种方式(百度经验有),前提是需要注册谷歌账号(巨坑,输入电话验证的时候,要把前面空格去掉,对,它系统自己给你带了个空格)

 

3.详细过程:

3.1 根据视频前半截,练习 tkinter基础 与学会用  tkinter库资料

  • Tk:pass
  • mainloop:pass
  • Entry:It is used to input the single line text entry from the user.(用于输入单行文本) For multi-line text input, Text widget is used.(多行文本用Text)
  • Label: It refers to the display box where you can put any text or image which can be updated any time as per the code.(在显示框中放置文本或图像)标签控件;可以显示文本和位图
  • Button:To add a button in your application, this widget(小部件) is used.
  • canvas:画布控件;显示图形元素如线条或文本
  • bd: to set the border width(边宽) in pixels(像素).
  • bg: to set the normal background color.
  • cursor: to set the cursor(光标) used in the canvas.
  • highlightcolor: to set the color shown in the focus highlight.
  • width: to set the width of the widget.
  • height: to set the height of the widget.
  • command: to call a function.
  • font: to set the font on the button label.(控制字体)
  • image: to set the image on the button.
  • pack() :It organizes the widgets in blocks before placing in the parent widget.(包装)
  • grid() :It organizes the widgets in grid (table-like structure) before placing in the parent widget.(网格)
  • place():It organizes the widgets by placing them on specific positions directed by the programmer.;(位置)
# 1.建立窗口
import tkinter
m = tkinter.Tk()
''' 
widgets are added here 
'''
m.mainloop() 
# 2.
import tkinter as tk
root = tk.Tk()
root.title('Counting Seconds')   #窗口的名称
button = tk.Button(root, text='Stop', width=25, command=root.destroy)  #设置按钮
button.pack()   
w =tk.Label(root, text='GeeksForGeeks.org!')
w.pack() 
root.mainloop()
# 3.
from tkinter import *
master = Tk() 
Label(master, text='First Name').grid(row=0) 
Label(master, text='Last Name').grid(row=1) 
e1 = Entry(master) 
e2 = Entry(master) 
e1.grid(row=0, column=1) 
e2.grid(row=1, column=1) 
mainloop() 

3.2 requests(这个方面不太清楚,能模糊理解几个关键词的意思,后面会慢慢补充,此篇博客只是简单运用而已)

requests:它是一个Python第三方库,处理URL资源特别方便

3.3跟着视频实操(一定要动手,适当暂停多次尝试)

 

3.3.1 引入模块(提前下载)

import tkinter as tk
import requests

 

3.3.2 建一个页面,并设置成自己喜欢的大小

import tkinter as tk
import requests

HEIGHT = 400
WIDTH = 500

root = tk.Tk()

canvas = tk.Canvas(root,height=HEIGHT,width=WIDTH)
canvas.pack()
root .title ('my first Python program')

root.mainloop()

 

3.3.3设置按钮/标签/设置颜色等

import tkinter as tk
import requests

HEIGHT = 400
WIDTH = 500

root = tk.Tk()

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

root .title ('my first Python program')

frame = tk.Frame(root,bg='#80c1ff',bd=5)  #frame:框架,构架 bd:边宽
frame.place(relx=0.5,rely=0.1,relwidth=0.75,relheight=0.1,anchor='n')  #relx:指与左边距离,rely:与上边的距离

button = tk.Button(frame,text="Get Weather",bg='gray',font=('courier',10),command='')
button.place(relx=0.7,relwidth=0.3,relheight=1) # font:字体及大小,cammand:为命令

root.mainloop()

 

3.3.4 这里将frame与lower_frame对比,体会一下,frame的涵义

import tkinter as tk
import requests

HEIGHT = 400
WIDTH = 500

root = tk.Tk()

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

root .title ('my first Python program')

frame = tk.Frame(root,bg='#80c1ff',bd=5)  #frame:框架,构架 bd:边宽
frame.place(relx=0.5,rely=0.1,relwidth=0.75,relheight=0.1,anchor='n')  #relx:指与左边距离,rely:与上边的距离

button = tk.Button(frame,text="Get Weather",bg='gray',font=('courier',10),command='')
button.place(relx=0.7,relwidth=0.3,relheight=1) # font:字体及大小,cammand:为命令

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

lable = tk.Label(lower_frame,font=('courier',15))
lable.place(relwidth=1,relheight=1)

root.mainloop()

 

3.3.5体会Entry

import tkinter as tk
import requests

HEIGHT = 400
WIDTH = 500

root = tk.Tk()

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

root .title ('my first Python program')

frame = tk.Frame(root,bg='#80c1ff',bd=5)  #frame:框架,构架 bd:边宽
frame.place(relx=0.5,rely=0.1,relwidth=0.75,relheight=0.1,anchor='n')  #relx:指与左边距离,rely:与上边的距离

entry = tk.Entry(frame,font=40,fg='green')
entry.place(relwidth=0.65,relheight=1)

button = tk.Button(frame,text="Get Weather",bg='gray',font=('courier',10),command='')
button.place(relx=0.7,relwidth=0.3,relheight=1) # font:字体及大小,cammand:为命令

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

lable = tk.Label(lower_frame,font=('courier',15))
lable.place(relwidth=1,relheight=1)

root.mainloop()

 

3.3.6注册openweathermap (前面已经将我遇到的坑交代了,剩下的靠自己了)

       看视屏吧,我传不了截图。。。我太菜。不懂的留言就行

3.3.7

非常重要的事:从注册完之后,就不能抄视频里面的了,因为有变化,而且,要确保能懂点英文,懂点python基础,才能进行接下来的工作。

注意button 那一行的变化,command变化了

import tkinter as tk
import requests

HEIGHT = 400
WIDTH = 500

'''
'''
def get_weather(city):
    weather_key = 'd918307fea274e3a6812dbe2296fb205'
    url = 'http://api.openweathermap.org/data/2.5/forecast'
    params = {'APPID':weather_key,'q':city}
    response = requests.get(url,params=params)
    print(response.json())
   # weather = (response.json())
   # lable['text'] = format_response(weather)


root = tk.Tk()

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

root .title ('my first Python program')

frame = tk.Frame(root,bg='#80c1ff',bd=5)  #frame:框架,构架 bd:边宽
frame.place(relx=0.5,rely=0.1,relwidth=0.75,relheight=0.1,anchor='n')  #relx:指与左边距离,rely:与上边的距离

entry = tk.Entry(frame,font=40,fg='green')
entry.place(relwidth=0.65,relheight=1)

button = tk.Button(frame,text="Get Weather",bg='gray',font=('courier',10),command=lambda: get_weather(entry.get()))
button.place(relx=0.7,relwidth=0.3,relheight=1) # font:字体及大小,cammand:为命令

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

lable = tk.Label(lower_frame,font=('courier',15))
lable.place(relwidth=1,relheight=1)

root.mainloop()

 

3.3.8 注意两个函数

import tkinter as tk
import requests

HEIGHT = 400
WIDTH = 500

def format_response(weather):
    try:
        name = weather['city']['name']
        desc = weather['list'][0]['weather'][0]['description']
        temp = weather['list'][0]['main']['temp']

        return ('City:%s \n Conditions:%s \n Temperature(℉):%s \n' %(name,desc,temp))
    except:
        return 'There was a problem \n retrieving that information'



def get_weather(city):
    weather_key = 'd918307fea274e3a6812dbe2296fb205'
    url = 'http://api.openweathermap.org/data/2.5/forecast'
    params = {'APPID':weather_key,'q':city}
    response = requests.get(url,params=params)
    # print(response.json())
    weather = (response.json())
    lable['text'] = format_response(weather)


root = tk.Tk()

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

root .title ('my first Python program')

frame = tk.Frame(root,bg='#80c1ff',bd=5)  #frame:框架,构架 bd:边宽
frame.place(relx=0.5,rely=0.1,relwidth=0.75,relheight=0.1,anchor='n')  #relx:指与左边距离,rely:与上边的距离

entry = tk.Entry(frame,font=40,fg='green')
entry.place(relwidth=0.65,relheight=1)

button = tk.Button(frame,text="Get Weather",bg='gray',font=('courier',10),command=lambda: get_weather(entry.get()))
button.place(relx=0.7,relwidth=0.3,relheight=1) # font:字体及大小,cammand:为命令

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

lable = tk.Label(lower_frame,font=('courier',15))
lable.place(relwidth=1,relheight=1)

root.mainloop()

4.第一次代码: 

准备改进的地方:

(1)、添加背景图片,增加更多信息,添加天气等图标

(2) 、理解requests

​import tkinter as tk
import requests

HEIGHT = 400
WIDTH = 500

def format_response(weather):
    try:
        name = weather['city']['name']
        desc = weather['list'][0]['weather'][0]['description']
        temp = weather['list'][0]['main']['temp']

        return ('City:%s \n Conditions:%s \n Temperature(℉):%s \n' %(name,desc,temp))
    except:
        return 'There was a problem \n retrieving that information'



def get_weather(city):
    weather_key = 'd918307fea274e3a6812dbe2296fb205'
    url = 'http://api.openweathermap.org/data/2.5/forecast'
    params = {'APPID':weather_key,'q':city}
    response = requests.get(url,params=params)
    # print(response.json())
    weather = (response.json())
    lable['text'] = format_response(weather)

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

# d918307fea274e3a6812dbe2296fb205
# api.openweathermap.org/data/2.5/forecast?q={city name}&appid={your api key}

'''
background_image = tk.PhotoImage(file=)
background_label = tk.Lable(root,image=background_image)
background_lable.place(relwidth=1,relheight=1)
'''

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

entry = tk.Entry(frame,font=40,fg='green')
entry.place(relwidth=0.65,relheight=1)

button = tk.Button(frame,text="Get Weather",bg='gray',font=('courier',10),command=lambda: get_weather(entry.get()))
button.place(relx=0.7,relwidth=0.3,relheight=1)

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

lable = tk.Label(lower_frame,font=('courier',15))
lable.place(relwidth=1,relheight=1)

root.mainloop()​

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,首先你需要注册一个气象数据提供商的API账号。这里我们以和风天气为例,注册地址:https://dev.heweather.com/ 注册完成后,你可以在官网上获取到自己的API Key。然后,我们就可以开始编写代码了。 首先,我们需要导入需要的库: ```python import requests import tkinter as tk from tkinter import messagebox ``` 然后,我们定义一个函数,用来调用API并获取天气信息: ```python def get_weather(city): url = 'https://free-api.heweather.net/s6/weather/now?location={}&key=你的API Key'.format(city) response = requests.get(url) if response.status_code == 200: data = response.json() if data['HeWeather6'][0]['status'] == 'ok': weather = data['HeWeather6'][0]['now'] return weather else: messagebox.showerror('错误', '城市名输入有误,请重新输入!') else: messagebox.showerror('错误', '网络异常,请稍后重试!') ``` 在这个函数中,我们首先拼接出API请求的URL,然后使用requests库发送请求,并判断请求是否成功。如果成功,我们可以从返回的JSON数据中提取出当前天气信息,然后返回这个信息。如果请求失败,我们弹出一个提示框,告诉用户出现了什么问题。 接下来,我们可以编写一个GUI界面,让用户输入城市名并查询天气。界面代码如下: ```python class WeatherApp: def __init__(self): self.window = tk.Tk() self.window.title('天气查询') self.window.geometry('300x150') self.label = tk.Label(self.window, text='请输入城市名:') self.label.pack() self.entry = tk.Entry(self.window) self.entry.pack() self.button = tk.Button(self.window, text='查询', command=self.show_weather) self.button.pack() self.result = tk.Label(self.window, text='') self.result.pack() self.window.mainloop() def show_weather(self): city = self.entry.get() weather = get_weather(city) if weather: self.result.config(text='当前温度为{}摄氏度,天气{}'.format(weather['tmp'], weather['cond_txt'])) ``` 在这个界面中,我们使用了tkinter库来创建窗口、标签、输入框、按钮和文本框。当用户点击查询按钮时,我们调用get_weather函数查询天气信息,并在文本框中显示查询结果。 最后,我们可以创建一个WeatherApp对象,启动这个应用程序: ```python app = WeatherApp() ``` 现在,你就可以使用这个简单的应用程序来查询天气了。注意,你需要将代码中的“你的API Key”替换成你自己的API Key。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值