Skip to content

Instantly share code, notes, and snippets.

@D4koon
Last active April 9, 2020 18:31
Show Gist options
  • Save D4koon/bbb4f59e6a5921d71a6d2aba0f60472d to your computer and use it in GitHub Desktop.
Save D4koon/bbb4f59e6a5921d71a6d2aba0f60472d to your computer and use it in GitHub Desktop.
Simple example parsing an XML and showing it in an Treeview
#-*- encoding: utf8 -*-
# Call with "python parseXML.py test.xml"
from tkinter import *
from tkinter.ttk import Treeview
import xml.etree.ElementTree as ET
class App:
def __init__(self, root):
try:
with open(sys.argv[1]) as f:
read_data = f.read()
rootNode = ET.fromstring(read_data)
self.tree = Treeview(root)
self.tree.pack(expand=True, fill='both')
self.walk_dict(rootNode)
except Exception as e:
print(e)
def walk_dict(self, d, depth=0, parent=""):
for child in d:
print(child.tag, child.attrib)
nodeName = child.tag + " - " +child.attrib.__str__()
# With None a unique id is generated automatically.
item = self.tree.insert(parent, 'end', None, text=nodeName)
if child.__len__() > 0:
self.walk_dict(child, depth + 1, parent=item)
else:
# With None a unique id is generated automatically.
if(child.text != None):
self.tree.insert(item, 'end', None, text=child.text)
gui = Tk()
gui.geometry("500x600")
App(gui)
gui.mainloop()
<menu>
<opcao1 kind="func">
<lol></lol>
</opcao1>
<opcao2>Tomate frito</opcao2>
<opcao3></opcao3>
<opcao4>Churrasco de ovelha</opcao4>
<opcao5>Pizza</opcao5>
<opcao6>
<lol>Copter</lol>
<meh>lolcopter</meh>
<bla>
<woo>foo</woo>
</bla>
</opcao6>
</menu>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment