Tkinter Text New Document
In the design of the editing program, sometimes you want to create a new document, when the editing program will empty the editing area for editing a new document. It is designed in the following way.
(1) delete the content of the Text control, you can refer to the following procedures, line 6.
(2) the window title to "Untitled", you can refer to the following procedures, line 7.
Example#1
In the File menu to add New File command. Readers need to pay attention to lines 5 to 7 of the new document method newFile
. in addition, in line 30 in the File menu to create the New File command.
from tkinter import *
from tkinter.filedialog import asksaveasfilename
def newFile():
text.delete("1.0",END)
root.title("apidemos-new")
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="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)
text.insert(END,"Five Hundred Miles\n") # Set Tag at the same time when inserting
text.insert(END,"If you miss the rain I am on,\n")
text.insert(END,"You will knw that I am gone.\n")
text.insert(END,"You can hear the whistle blw\n")
text.insert(END,"A hunded miles,\n")
root.mainloop()
Output: