You need to enable JavaScript to run this app. 如何在Tkinter窗口中运行Python函数并展示爬虫抓取的天气数据
优惠活动
大模型
产品
解决方案
定价
更多

如何在Tkinter窗口中运行Python函数并展示爬虫抓取的天气数据

实现方案

核心逻辑是将原来weather_def函数中直接打印到终端的内容,拼接为完整字符串返回,再在Tkinter的点击回调中更新界面组件的展示内容。


步骤1:修改weather.py文件

将打印逻辑替换为字符串拼接,同时把页面请求逻辑移入函数内部,避免仅第一次请求能拿到最新数据:

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

def weather_def():
    url_weather = 'https://www.mein-wetter.com/wetter/ebermannstadt.htm'
    # 打开连接抓取页面
    uClient_weather = uReq(url_weather)
    page_html_weather = uClient_weather.read()
    uClient_weather.close()

    # 解析HTML
    page_soup_weather = soup(page_html_weather, "html.parser")
    containers_weather = page_soup_weather.find('ul', {'class': 'uldet'}).findAll('li')

    # 初始化结果字符串
    res = "Wetter\n"
    res += "::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n"

    for container in containers_weather:
        time = container.findAll('h4')[0].text
        temperature = container.findAll('dd', {'class': 'temp'})[0].text
        image_alt = container.find('img').get('alt')
    
        # 仅展示6:00到23:00的天气
        if int(time) == 0:
            break
        elif int(time[1]) >= 6 or int(time[0]) > 0:
            res += f"{time}:00 Uhr\n"
            res += f"{temperature}\n"
            res += f"{image_alt}\n"
            res += "-----------------------------------------\n"
    return res

步骤2:修改Tkinter主程序代码

新增点击回调函数,调用天气函数拿到结果后更新界面展示。如果要展示多行内容,建议将原来的单行Label替换为多行Text组件,展示效果更好:

from tkinter import *
from PIL import ImageTk, Image
from weather import weather_def 

# 主窗口初始化
window = Tk()
window.title('My Overview')
window.configure(background='white')
# 调整窗口大小适配多行内容
window.geometry("400x500")

# 输入框
textentry = Entry(window, width=15, bg='white')
textentry.place(x=80, y=40)

# 新增多行文本展示组件,替代原来的Label
result_text = Text(window, bg='white', fg='black', font='none 12')
result_text.place(x=80, y=120, width=280, height=300)        

# 点击回调函数
def show_weather():
    # 先清空原有内容
    result_text.delete(1.0, END)
    # 获取天气结果
    weather_info = weather_def()
    # 插入到文本组件
    result_text.insert(END, weather_info)

# 提交按钮绑定回调函数
btn = Button(window, text='Show information', command=show_weather, width=10)
btn.place(x=80, y=80)

window.mainloop()

可选说明

如果坚持使用原来的Label组件展示,只需要把回调函数里的文本组件操作替换为label.config(text=weather_info)即可,但Label默认不支持滚动,内容过多会被截断。

内容的提问来源于stack exchange,提问作者jumuell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 03:15:04