鱼C论坛

 找回密码
 立即注册
查看: 1512|回复: 0

[作品展示] 第一个小程序:天气查询

[复制链接]
发表于 2022-3-18 16:52:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
根据前辈们爬天气的代码加上GUI页面,目前有个问题就是运行一次只能查询一次,再次查询需要重新运行,有没有大佬帮忙优化一下


import tkinter
import requests
import pypinyin
from bs4 import BeautifulSoup
from tkinter import messagebox
def inp():
    city = ''
    chengshi = en1.get()
    chengshi =chengshi.strip()
    if chengshi == '':
        messagebox.showinfo("温馨提示", "城市不能为空")
    else:
        for each in chengshi:
            city = city + pypinyin.pinyin(each, style=pypinyin.NORMAL)[0][0]
    return city,chengshi
def get(city, cityname_zh):
    url = "https://www.tianqi.com/"+ city +"/"
    headers = {
        'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36'
        }
    res = requests.get(url, headers=headers).text
    soup = BeautifulSoup(res, 'html.parser')
    du = soup.find("p", class_="now")
    shidu_atart = soup.find("dd", class_="shidu")
    tianqi = soup.find("dd", class_="weather")
    shidu = shidu_atart.find_all("b")
    text = str(cityname_zh+"市天气预报\n---------------------"+"\n天气:"+tianqi.span.b.text+"\n"+"温度:"+du.b.text+"摄氏度"+"\n"+shidu[0].text+"\n"+shidu[1].text+"\n"+shidu[2].text)
    la2 = tkinter.Label(root, width=200, height=300, background="#FFFFFF", borderwidth=2, text=text)
    la2.pack()
def run():
    c, y = inp()
    get(city=c, cityname_zh=y)
root = tkinter.Tk()
root.geometry("400x500")
root.title("天气查询")
la1 = tkinter.Label(root, text="请输入城市")
la1.pack()
en1 = tkinter.Entry(root)
en1.pack()
ba = tkinter.Button(root, text="查询", command=run)
ba.pack()
root.mainloop()
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-29 13:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表