Tkinter Open Document
In tkinter.filedialog
module has askopenfilename()
method, you can use this method, so that the window appears dialog box, and then the implementation of the selection of the document to be opened.
filename = askopenfilename()
The above procedure can be passed back to the path of the document stored in the disk (including the folder), then you can use the open ( ) method to open the document, and finally the document opened into the Text control. Steps are as follows.
(1) in the open dialog box to select the document you want to open, you can refer to the following procedures, line 12.
(2) use the open File ( ) method to open the document, you can refer to the following procedures, line 15.
(3) use read ( ) method to read the contents of the document, you can refer to the following procedures, line 16.
(4) delete the content of the Text control, you can refer to the following procedures, line 17.
(5) will read the contents of the document inserted into the Text control, you can refer to the following procedures, line 18.
(6) change the name of the window title, refer to the following procedure, line 19.
Example#1
Add the application of Open Document Open. When this program is executed, you can use the File→Open command to open a document, and then store the opened document in the Text control, while changing the window title to the path of the opened document.
from tkinter import *
from tkinter.filedialog import asksaveasfilename
from tkinter.filedialog import askopenfilename
def newFile():
text.delete("1.0",END)
root.title("Untitled")
def openFile():
global filename
filename = askopenfilename()
if filename == "":
return
with open(filename,"r") as fileObj:
content = fileObj.read()
text.delete("1.0",END)
text.insert(END,content)
root.title(filename)
def saveAsFile():
global filename
textContent = text.get("1.0",END)
filename = asksaveasfilename(defaultextension=".txt")
print("The file path passed back is : ",filename)
if filename == "":
return
with open(filename,"w") as output:
output.write(textContent)
root.title(filename)
filename = "apidemos"
root = Tk()
root.title(filename)
root.geometry("300x180")
menubar = Menu(root) # Create top-level menu
# Create a menu category object and name this menu File
filemenu = Menu(menubar,tearoff=False)
menubar.add_cascade(label="File",menu=filemenu)
# Create a menu list within the File menu
filemenu.add_command(label="New File",command=newFile)
filemenu.add_command(label="Open File ...",command=openFile)
filemenu.add_command(label="Save As ...",command=saveAsFile)
filemenu.add_separator()
filemenu.add_command(label="Exit",command=root.destroy)
root.config(menu=menubar)
# Create Text
text = Text(root,undo=True)
text.pack(fill=BOTH,expand=True)
root.mainloop()
Output:
When the Open
button is clicked, the following results can be obtained by moderately enlarging the window.