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

Tkinter Map View报错:'PhotoImage'对象无'_PhotoImage__photo'属性

问题解决:tkintermapview绘制多边形出现AttributeError错误

错误原因

你的代码存在循环嵌套逻辑错误:在交换单个坐标点的经纬度时就调用set_polygon,导致每次只处理一个坐标点就尝试绘制多边形,传递给地图组件的是不完整的坐标列表,引发内部PhotoImage对象的引用管理异常,从而抛出AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'。

修复方案

  1. 先完成所有坐标点的经纬度交换,再调用set_polygon绘制当前地方当局的多边形
  2. 补充导入tkinter.messagebox模块(原代码中使用了但未导入)
  3. 优化循环变量命名,避免内外层循环变量重名引发逻辑混乱

修正后的完整代码

import tkinter as tk
import tkintermapview
import tkinter.messagebox as messagebox
import json
import itertools

# 创建主窗口
root_tk = tk.Tk()
root_tk.geometry(f"{1000}x{700}")
root_tk.title("地方当局地图选择")

# 创建地图组件
map_widget = tkintermapview.TkinterMapView(root_tk, width=800, height=600, corner_radius=0)
map_widget.pack(fill="both", expand=True)
map_widget.set_position(53.46, -2.250)  # 设置英国为中心
map_widget.set_zoom(8)

# 多边形点击事件处理
def UpdateMap(event=None):
    messagebox.showinfo("提示", "选中了一个地方当局")

# 加载地方当局边界数据
with open('LA_shape.json', 'r', encoding='utf-8') as d:
    shape = json.load(d)
shape = shape['features']

# 遍历每个地方当局
for la_idx in range(len(shape)):
    coord = shape[la_idx]['geometry']['coordinates']
    # 处理MultiPolygon结构,展平坐标
    coord = list(itertools.chain(*coord))
    coord = list(itertools.chain(*coord))
    
    # 交换所有坐标的经纬度顺序(适配地图组件的坐标要求)
    for point_idx in range(len(coord)):
        coord[point_idx][0], coord[point_idx][1] = coord[point_idx][1], coord[point_idx][0]

    # 绘制当前地方当局的多边形
    map_widget.set_polygon(coord,
        fill_color="#ff000020",  # 半透明红色填充,便于查看底层地图
        outline_color="red",
        border_width=2,
        command=UpdateMap,
        name=f"local_authority_{la_idx}")
    
root_tk.mainloop()

额外说明

  • 使用with open语句加载JSON文件,确保文件正确关闭
  • 给每个多边形设置唯一的name属性,便于后续管理
  • 添加了填充色和边框样式,提升多边形的可见性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:12:59