You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter天气应用问题:按钮无法传递城市参数调用OpenWeather API

问题分析与修复方案

核心问题点

  1. city变量初始化时机错误:city = entry1.get()在程序启动时就执行,此时输入框无内容,city始终为空,不会随用户输入更新。
  2. 按钮command参数错误:按钮的command需要传入可调用函数,而非直接传变量city,这会导致点击按钮时触发错误。
  3. API请求触发时机错误:当前代码在窗口启动前就执行API请求,未绑定到按钮点击事件,无法实现“点击搜索才查询”的逻辑。

修复后的完整代码

from tkinter import *
import tkinter as tk
from geopy.geocoders import Nominatim
from tkinter import ttk,messagebox
from timezonefinder import TimezoneFinder
from datetime import datetime
from meteostat import Point, Daily
import requests
import pytz

api_key = "secret_api_key"

root=Tk()
root.title("Weather App")
root.geometry("900x500+300+200")
root.resizable(False,False)

#entry box
entry1 = Entry(root, width = 20)
entry1.place(relx=0.5, rely=0.5, anchor=CENTER)

#Title text
label1 = Label(root,text="Welcome to the weather app", font=("Arial", 24))
label1.place(x=300, y=150)

#Enter a location text
label2 = Label(root,text="Enter your city", font=("Arial", 14))
label2.place(x=400, y=200)

#weather graphic
Search_image=PhotoImage(file="/Users/lucky/Downloads/cloudy (1).png")
myimage=Label(image=Search_image)
myimage.place(x=20,y=20)

def search_weather():
    # 点击按钮时获取输入框最新内容
    city = entry1.get().strip()
    if not city:
        messagebox.showwarning("提示", "请输入城市名称")
        return
    
    try:
        # 发送API请求
        weather_data = requests.get(
            f"https://api.openweathermap.org/data/2.5/weather?q={city}&units=imperial&APPID={api_key}")
        weather_data.raise_for_status()
        print(weather_data.json())
        # 此处可添加解析数据并展示到界面的逻辑
    except requests.exceptions.RequestException as e:
        messagebox.showerror("错误", f"查询天气失败:{str(e)}")

#search button
btn = Button(root, text="search", command=search_weather)
btn.place(x=450, rely=0.57, anchor=CENTER)

root.mainloop()

关键修复说明

  • 封装回调函数:新增search_weather函数,将获取城市、API请求逻辑整合,作为按钮点击的触发逻辑。
  • 延迟获取输入内容:在函数内部调用entry1.get(),确保每次点击都能拿到输入框的最新值。
  • 输入校验与异常处理:添加空输入判断和API请求错误捕获,通过弹窗提示用户,提升程序稳定性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 02:35:21