优化上一篇的gui界面生成

复制代码
import pandas as pd
import json
import datetime
import os
import tkinter as tk
from tkinter import filedialog


def convert_to_excel():
    now = datetime.datetime.now()
    formatted_time = now.strftime("%Y-%m-%d_%H-%M-%S")

    # Open file dialog for selecting a file
    file_path = filedialog.askopenfilename(filetypes=[('Text files', '*.txt')])

    # Check if a file was selected
    if file_path:
        # Read JSON data from the selected file with permissive error handling
        with open(file_path, 'r', encoding='utf-8', errors='replace') as file:
            json_data = json.load(file)

        # Extract the 'data' part from JSON
        data_list = json_data.get("data", [])

        # Convert to DataFrame
        df = pd.DataFrame(data_list)

        # Save the DataFrame to an Excel file
        output_file_path = f"{formatted_time}.xlsx"
        df.to_excel(output_file_path, index=False)

        # Display a success message
        result_label.config(text=f"Conversion successful. File saved as {output_file_path}")


# Create the main application window
app = tk.Tk()
app.title("JSON to Excel Converter")

# Calculate the center coordinates for the window
screen_width = app.winfo_screenwidth()
screen_height = app.winfo_screenheight()
window_width = 400  # Adjust the width as needed
window_height = 150  # Adjust the height as needed

x_position = (screen_width - window_width) // 2
y_position = (screen_height - window_height) // 2

# Set the window geometry
app.geometry(f"{window_width}x{window_height}+{x_position}+{y_position}")

# Create a button for converting to Excel
convert_button = tk.Button(app, text="Convert to Excel", command=convert_to_excel)
convert_button.pack(pady=20)

# Create a label for displaying the result message
result_label = tk.Label(app, text="")
result_label.pack()

# Run the application loop
app.mainloop()
相关推荐
浊酒南街4 分钟前
决策树python实现代码1
python·算法·决策树
FreedomLeo11 小时前
Python机器学习笔记(十三、k均值聚类)
python·机器学习·kmeans·聚类
星光樱梦1 小时前
32. 线程、进程与协程
python
阿正的梦工坊1 小时前
深入理解 PyTorch 的 view() 函数:以多头注意力机制(Multi-Head Attention)为例 (中英双语)
人工智能·pytorch·python
西猫雷婶2 小时前
python学opencv|读取图像(十九)使用cv2.rectangle()绘制矩形
开发语言·python·opencv
海绵波波1072 小时前
flask后端开发(10):问答平台项目结构搭建
后端·python·flask
赵谨言3 小时前
基于python网络爬虫的搜索引擎设计
爬虫·python·搜索引擎
code04号3 小时前
python脚本:批量提取excel数据
开发语言·python·excel
hakesashou3 小时前
python如何打乱list
开发语言·python
silver6874 小时前
使用 Python 操作 Excel 表格
python