Tkinter Default ScrolledText control with scrollbars
Tkinter Text Add Scrollbar design Introduced the binding of scrollbars in the Text control, in fact, the previous design of a simple text editing program without scrollbars, formal text editing program should be designed to scrollbars, we can use the method of Section 17-3 plus scrollbars. Alternatively, you can use the tkinter control with scrollbars to design this kind of program. In the tkinter.scrolledtext module, there is the ScrolledText control, which is a Text control with a scroll bar by default.
Example#1
Use the ScrolledText control to replace the Text control. The following is the content of the 4th line added when importing this module, and then create the ScrolledText to replace the content of the Text control.
from tkinter import *
from tkinter.filedialog import asksaveasfilename
from tkinter.filedialog import askopenfilename
from tkinter.scrolledtext import ScrolledText #as Text
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 = ScrolledText(root,undo=True)
text.pack(fill=BOTH,expand=True)
root.mainloop()
Output:
Open apidemos2.txt