EDIT: Yes, I have a similar problem as the link below but I don’t think this is a duplicate question because unfortunately, the answer doesn’t solve my problem. How come a file doesn't get written until I stop the program?
I tried the f=open(file,w)
f.close()
f.flush()
os.fsync(f)
and it didn’t help. Please also note that I am using with
statement that should accomplish the same thing as once the Python exits from the with
block, the file is automatically closed.
Even all that the file still doesn’t get written until I close the program.
I also noticed now that this is not a Tkinter problem as I thought first, the problem exist without the Tkinter GUI. Might be something to do with the lxml.etree
ORIGINAL QUESTION BELOW
I have tried to make a simple GUI for the XML converter script.
I am having problems when saving the file. The file doesn’t get written until I close or destroy() the Tkinter program. Can anyone explain why that would happen and how to fix it? I would like to write the file while the Tkinter window is running.
Please find below the code:
from tkinter import *
import lxml.etree as ET
import tkinter.filedialog as fdialog
def mfileopen():
global xml_file
xml_file = fdialog.askopenfile()
Label(text=xml_file) .pack()
def dropdown_select(selection):
global xslt_file
if selection == "Stylesheet 1":
xslt_file = "stylesheet1.xsl"
elif selection == "Stylesheet 2":
xslt_file = "stylesheet2.xsl"
def convert_xml(xslt_file, input_xml):
dom = ET.parse(input_xml)
xslt = ET.parse(xslt_file)
transform = ET.XSLT(xslt)
newdom = transform(dom)
write_file(newdom)
def write_file(csv_file):
with open("output.csv", "w") as f:
f.write(str(csv_file))
OPTIONS = [
"Stylesheet 1",
"Stylesheet 2",
]
master = Tk()
Label (text="Open XML file and then Choose XSLT Code from the dorpdown menu and press Load XSLT. Finally press Convert XML") .pack()
button = Button(text="Open XML File", width=30, command=mfileopen)
button.pack()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
button = Button(master, text="Load XSLT", command=lambda: dropdown_select(variable.get()))
button.pack()
button = Button(master, text="Convert XML", command=lambda: convert_xml(xslt_file, xml_file))
button.pack()
master.mainloop()