对于Python不熟悉的同学,建议从本专栏第一篇开始观看
https://blog.csdn.net/qq_20330595/category_12844705.html
先上效果图
代码
import threading
import tkinter as tk
import json
from tkinter import scrolledtext
import tkinter.filedialog as filedialog
class JsonParserGUI:
def __init__(self):
self.root = tk.Tk()
self.root.title("字符串转JSON")
self.text_area = scrolledtext.ScrolledText(self.root, width=80, height=20)
self.text_area.pack(fill=tk.BOTH, expand=1)
# self.text_area = tk.Text(self.root)
# self.text_area.pack(fill=tk.BOTH, expand=1)
self.button_frame = tk.Frame(self.root)
self.button_frame.pack(fill=tk.X)
self.parse_button = tk.Button(self.button_frame, text="Parse JSON", command=self.parse_json)
self.parse_button.pack(side=tk.LEFT)
self.open_button = tk.Button(self.button_frame, text="Open File", command=self.open_file_thread)
self.open_button.pack(side=tk.LEFT)
def parse_json(self):
try:
json_data = json.loads(self.text_area.get(1.0, tk.END))
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, json.dumps(json_data, indent=4))
except json.JSONDecodeError as e:
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, f"Error: {e}")
def open_file_thread(self):
thread = threading.Thread(target=self.open_file)
thread.start()
def open_file(self):
file_path = tk.filedialog.askopenfilename()
if file_path:
with open(file_path, 'r') as file:
file_content = file.read()
self.update_text_area_thread(file_content)
def update_text_area_thread(self, file_content):
thread = threading.Thread(target=self.update_text_area, args=(file_content,))
thread.start()
def update_text_area(self, json_data):
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, json_data)
def run(self):
self.root.mainloop()
if __name__ == "__main__":
gui = JsonParserGUI()
gui.run()
def save_string_to_file(string, filename):
with open(filename, 'w') as file:
file.write(string)