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

天气应用报错AttributeError: 'NoneType'对象无'longitude'属性求助

问题分析与解决方案

代码中的核心问题

  • 文本获取错误:textfield.get未调用方法,需改为textfield.get()——否则city存储的是方法对象而非实际输入的城市名称,导致地理编码请求无效。
  • 未处理异常场景:若输入城市名称无效,geolocator.geocode(city)会返回None,此时直接访问location.longitude会触发AttributeError。

修正后的代码

def getWeather():
    # 正确获取输入框中的城市名称
    city = textfield.get()
    
    # 检查输入是否为空
    if not city.strip():
        print("请输入有效的城市名称")
        return
    
    geolocator = Nominatim(user_agent="geoapiExercises")
    location = geolocator.geocode(city)
    
    # 确认地理编码是否成功找到城市
    if not location:
        print("无法定位该城市,请检查名称拼写")
        return
    
    obj = TimezoneFinder()
    result = obj.timezone_at(lng=location.longitude, lat=location.latitude)
    print(result)

关键修正说明

  1. 补全get()方法调用,确保获取到用户输入的文本内容。
  2. 增加输入合法性校验,避免空字符串或纯空格的无效请求。
  3. 增加地理编码结果的空值判断,提前拦截无效定位的情况,防止后续代码报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:10:31