基于PythonTkinter的JSON结构转化器

       自从上次发布一篇技术博客又过去了一个多月,因为12月份的疫情放开,从而导致博客阅读量从两位数,降到了个位数,我的内心是如此地无言以对...虽然疫情的冲击是客观因素,但作品质量的高低才应该是阅读量多少的主要因素...最近一直都在积极整理之前写的程序代码,但质量参差不齐,代码量有多有少(有些程序的代码还需要校正),而因平常工作忙碌等种种的原因,想完成高质量的一篇技术博客,实在是比较困难, 但本着分享是一种快乐的事情,因此还是按照一月一篇技术博客的节奏坚持好这个习惯,废话少说,直接开始内容吧!

        这是个JSON的结构转化器,将JSON的文本(可编辑)转化成树形结构图,方便使用者JSON的数据结构。注意:因为代码本身比较简单,所以并没有做分段注释!

主界面

树形图显示效果

文本紧凑模式
文本缩进模式

 代码开始

# encoding: utf-8
import os
from Tkinter import *
import re
import Pmw
import tkFileDialog
import ttk
import json

class Json_Edit():
    def __init__(self):
        self.root=Tk()
        self.root.title(u"JSON结构转化器")
        self.root.geometry("790x520")
        self.root.maxsize(790,520)
        self.root.minsize(790,520)
        self.root.iconbitmap('t_ico.ico')
        self._text=None
        self.show_information=StringVar()
        self.root_node=None
        #打开消息tK变量

    def open_cmd(self):
        #打开函数
        open_fpath=tkFileDialog.askopenfilename()
        try:
            file_txt=open(open_fpath,'r')
            text_file_context=file_txt.read(3000)
            file_txt.close()
            self._text.delete('1.0',END)
            self._text.insert(END,text_file_context.decode('cp936'),'text_file')
            self.show_information.set("打开成功!")
        except (IOError,Exception),e:
            print(e)

    def keep_cmd(self):
        #保存函数
        asd=tkFileDialog.asksaveasfilename()
        text_context=self._text.get('1.0',END)
        try:
            file_txt=open(asd,'w')
            file_txt.write(text_context.encode('cp936'))
            file_txt.close()
            self.show_information.set("保存成功!")
        except (IOError,Exception),e:
            pass
            print(e)

    def close_cmd(self):
        #关闭功能函数
        self.root.quit()
        os._exit(0)

    def clear_tree(self):
        #清空数树型图
        try:
            print(self.root_node)
            self.tree.delete(self.root_node)
            del self.root_node
            self.root_node=None
        except (AttributeError,Exception),e:
            pass

    def clear_comd(self):
        #清除函数
        self._text.delete('1.0',END)
        self.show_information.set("清空!")
        try:
            print(self.root_node)
            self.tree.delete(self.root_node)
            del self.root_node
            self.root_node=None
        except (AttributeError,Exception),e:
            pass
           
    def compact_comd(self):
        #紧凑函数(缩进反转)
        text_context=self._text.get('1.0',END)
        self._text.delete('1.0',END)
        str_text_context_comp=text_context.replace(' ','')
        str_text_context_comp=str_text_context_comp.replace('\n','')
        #self._text.insert(END,str_text_context_comp,'sss')
        #self.show_mess.configure(text="紧凑模式已处理!")
        self.show_information.set("紧凑模式已处理!")

    def refresh_comd(self):
        #刷新树形图函数
        def for_xunhuan(data,node_):
            
            if isinstance(data,dict):
                #添加树形结构点
                for kkk in data:
                    ch_node=self.tree.insert(node_,'end',text=kkk,open=False)
                    if isinstance(data[kkk],unicode)==True:
                        ch1_node=self.tree.insert(ch_node,'end',text=kkk+"(key)"+":"+data[kkk]+"(value)",open=False)
                    elif isinstance(data[kkk],list) or isinstance(data[kkk],dict):
                        for_xunhuan(data[kkk],ch_node)
                    else:
                        ch_node=self.tree.insert(node_,'end',text=kkk,open=False)
                    
            elif isinstance(data,list):
                for jjj in data:
                    if isinstance(jjj,list) or isinstance(jjj,dict):
                        for_xunhuan(jjj,node_)
                    else:
                        ch_node=self.tree.insert(node_,'end',text=jjj,open=False)
            else:
                pass
                    
                    
        text_context=self._text.get('1.0',END)
        if self.root_node==None:
            try:
                json_data=json.loads(text_context)
                self.root_node = self.tree.insert('','end',text='tree_view',tags="first_node",open=False)
                self.tree.tag_configure('first_node',background='blue')
                if isinstance(json_data,dict):
                    for_xunhuan(json_data,self.root_node)
                elif isinstance(json_data,list):
                    for_xunhuan(json_data,self.root_node)
                else:
                    root_node1=self.tree.insert(self.root_node,'end',text="<--over-->",open=False)
            except ValueError,e:
                self.show_information.set("输入字符有误,请重新检查!")
                
                self.tree.tag_configure('first_node',background='red')
            except UnboundLocalError,e:
                self.show_information.set(e)
                self.tree.tag_configure('first_node',background='red')
            else:
                self.show_information.set("树视图刷新完毕!")
                
                    
    def retract_comd(self):
        #缩进函数
        text_context=self._text.get('1.0',END)
        str_text_context=str(text_context.encode('cp936')).replace("\n","")
        space_str='    '
        str_text_context_lq=str_text_context.replace("[","[\n")
        str_text_context_rq=str_text_context_lq.replace("]","]\n")
        str_text_context_lb=str_text_context_rq.replace("{","{\n")
        str_text_context_rb=str_text_context_lb.replace("}","}\n")
        str_text_context_comma=str_text_context_rb.replace(",",",\n")
        str_text_context_color=str_text_context_comma.replace(":",":\n")
        str_text_context_dec_rq=str_text_context_color.replace("\"]","\"\n]")
        self._text.delete('1.0',END)
        self._text.insert(END,str_text_context_dec_rq.decode('cp936'),'sss')
        list_context=str_text_context_dec_rq.split('\n')
        for i in range(len(list_context)):
            if list_context[i].find('[')!=-1:
                for j in range(i+1,len(list_context)):
                    char_lq=str(list_context[j])
                    list_context[j]=space_str+char_lq
            elif list_context[i].find(']')!=-1:
                for jj in range(i,len(list_context)):
                    if list_context[jj][0:4]=="    ":
                        char_rq=str(list_context[jj])
                        list_context[jj]=char_rq[4:]
            elif list_context[i].find('{')!=-1:
                for j in range(i+1,len(list_context)):
                    char_lb=str(list_context[j])
                    list_context[j]=space_str+char_lb
            elif list_context[i].find('}')!=-1:
                for jj in range(i,len(list_context)):
                    if list_context[jj][0:4]=="    ":
                        char_rb=str(list_context[jj])
                        list_context[jj]=char_rb[4:]
            else:
                pass
        join_char='\n'.join(list_context)
        self._text.delete('1.0',END)
        self._text.insert(END,join_char.decode('cp936'),'sds')
        self.show_information.set("缩进模式已处理!")
        
    def main(self):
        #主界面函数
        self.menuBar=Pmw.MenuBar(self.root,hull_relief=RAISED,
                                 hull_borderwidth=1)
        self.menuBar.grid(row=0,column=0,columnspan=5,sticky=NSEW)
        self.menuBar.addmenu('选项',' Option',font=('Verdana bold',10))
        self.menuBar.addmenuitem('选项','command',label="打开",command=self.open_cmd,
                                 font=('Verdana bold',10),activebackground='blue')
        self.menuBar.addmenuitem('选项','command',label="保存",command=self.keep_cmd,
                                 font=('Verdana bold',10),activebackground='blue')
        self.menuBar.addmenuitem('选项','command',label="刷新",command=self.clear_comd,
                                 font=('Verdana bold',10),activebackground='blue')
        self.menuBar.addmenuitem('选项','command',label="关闭",command=self.close_cmd,
                                 font=('Verdana bold',10),activebackground='blue')
        self.left_frame=Frame(self.root,width=200)
        self.left_frame.grid(row=1,column=0,columnspan=2,rowspan=5,sticky=NSEW)
        button_s=Frame(self.left_frame,width=40,borderwidth=1)
        button_s.pack(side=TOP,fill=X, expand = 0,anchor='center')
        label_=Label(button_s,width=40,height=1,text="树形图")
        label_.pack(side=TOP,fill=X, expand = 0,anchor='center')
        tree_frame=Frame(self.left_frame,width=200)
        tree_frame.pack(side = 'top', fill = BOTH, expand = 1, padx = 1, pady = 1)
        self.tree = ttk.Treeview(tree_frame,selectmode="extended")
        xsb = ttk.Scrollbar(self.tree, orient='horizontal',command=self.tree.xview)
        ysb = ttk.Scrollbar(self.tree, orient='vertical',command=self.tree.yview)
        self.tree.configure(xscroll=xsb.set)
        self.tree.configure(yscroll=ysb.set)
        self.tree.heading('#0', text='', anchor='w')
        self.tree.column("#0",minwidth=500,width=500,stretch=NO)
        self.tree.pack(side = 'left', fill = BOTH, expand = 1, padx = 1, pady = 1)
        xsb.pack(side ='bottom',fill=BOTH)
        ysb.pack(side="right",fill = Y)
        
        self.right_frame=Frame(self.root)
        self.right_frame.grid(row=1,column=2,columnspan=2,rowspan=5,sticky=NSEW)
        self.but_=Frame(self.right_frame)
        self.but_.pack(side=TOP,anchor='w',padx=2)
        but_suojin=Button(self.but_,text="缩进",font=('Verdana bold',10),command=self.retract_comd)
        but_suojin.pack(side=LEFT)
        but_jincou=Button(self.but_,text="紧凑",font=('Verdana bold',10),command=self.compact_comd)
        but_jincou.pack(side=LEFT)
        but_shuaxin=Button(self.but_,text="刷新",font=('Verdana bold',10),command=self.refresh_comd)
        but_shuaxin.pack(side=LEFT)
        but_clear=Button(self.but_,text="清空",font=('Verdana bold',10),command=self.clear_tree)
        but_clear.pack(side=LEFT)
        
        self.text_frame=Frame(self.right_frame)
        self.text_frame.pack(side=TOP)
        
        self._text=Text(self.text_frame,height=24,width=53,font=('Verdana bold',10),selectbackground='blue')
        self._text.pack(side=LEFT)
        scroll=ttk.Scrollbar(self.text_frame,command=self._text.yview)
        self._text.configure(yscrollcommand=scroll.set)
        scroll.pack(side=RIGHT,fill=Y)
        self._text.mark_set('start','1.0')
        
        mess_frm=Frame(self.right_frame,width=200)
        mess_frm.pack(side=TOP,expand=1)
        wg=Pmw.Group(mess_frm,tag_text="消息显示")
        wg.pack(fill=BOTH,expand=1,padx=1,pady=1)
        self.show_mess=Label(wg.interior(),font=('Verdana bold',10),textvariable=self.show_information,relief=GROOVE,border=0,height=2,width=50)
        self.show_mess.pack(side=TOP,expand=1)
       
        self.root.mainloop()

if __name__== '__main__':
    instance=Json_Edit()
    instance.main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值