Json A12 计算总和

-*- coding: utf-8 -*-

import json

import tkinter as tk

from tkinter import filedialog, messagebox

def calculate_total():

try:

inputfile = file_entry.get()

if not inputfile:

messagebox.showerror("错误", "请先选择文件")

return

with open(inputfile, 'r', encoding='gbk') as f:

data = json.load(f)

total_a12 = 0

for feature in data['features']:

a12_str = feature['attributes']['A12']

if a12_str: # 确保A12不是空字符串

total_a12 += float(a12_str)

result_label.config(text=f"A12字段的总和为: {total_a12}")

except Exception as e:

messagebox.showerror("错误", f"计算过程中出现错误:\n{str(e)}")

def browse_file():

filename = filedialog.askopenfilename(

title="选择JSON文件",

filetypes=(("JSON文件", "*.json"), ("文本文件", "*.txt"), ("所有文件", "*.*"))

)

if filename:

file_entry.delete(0, tk.END)

file_entry.insert(0, filename)

创建主窗口

root = tk.Tk()

root.title("A12字段总和计算器")

root.geometry("500x200")

文件选择部分

file_frame = tk.Frame(root)

file_frame.pack(pady=10)

tk.Label(file_frame, text="文件路径:").pack(side=tk.LEFT)

file_entry = tk.Entry(file_frame, width=40)

file_entry.pack(side=tk.LEFT, padx=5)

browse_button = tk.Button(file_frame, text="浏览...", command=browse_file)

browse_button.pack(side=tk.LEFT)

计算按钮

calc_button = tk.Button(root, text="计算总和", command=calculate_total)

calc_button.pack(pady=10)

结果显示

result_label = tk.Label(root, text="", font=('Arial', 12))

result_label.pack(pady=20)

运行主循环

root.mainloop()