Tkinter Text Cut/Copy/Paste Function
Edit file cut / copy / paste is a very common function, these functions have actually been built in tkinter, but before using these built-in functions, the author still want to establish the correct concept for the reader to learn more basic skills, after all, learn the basics can understand the working principle, will be more helpful to the reader. If we want to delete the edited file can use the delete( ) method, in this method if you want to delete is a character, you can use a parameter, this parameter can be indexed, the following is an example.
delete(INSERT) # Delete the insertion point character
If you want to delete the selected text block, you can use two parameters: the start index and the end index.
delete(SEL_FIrST, SEL_LAST) # Delete the selected text block
delete(startindex, endindex) # Delete the text block in the specified area
When editing a program it is often necessary to delete the entire file, you can use the following syntax.
delete(1.0, END)
Note: All of the above need to be started by the Text object. Next, we will explain how to apply these functions directly with program examples.
Example#1
Use tkinter to design pop-up menus with Cut/Copy/Paste functions, which can perform Cut/Copy/Paste work.
from tkinter import *
from tkinter import messagebox
def cutJob(): # Cut method
print("Cut operation in progress...")
copyJob() # Copy selected text
text.delete(SEL_FIRST,SEL_LAST) # Delete selected text
def copyJob():
print("Copy operation in process...")
try:
text.clipboard_clear()
copyText = text.get(SEL_FIRST,SEL_LAST)
text.clipboard_append(copyText)
except TclError:
print("Not selected...")
def pasteJob():
print("Paste operation is in progress...")
try:
copyText = text.selection_get(selection="CLIPBOARD")
text.insert(INSERT,copyText)
except TclError:
print("No data on the clipboard")
def showPopupMenu(event):
print("Show pop-up menu...")
popupmenu.post(event.x_root,event.y_root)
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
popupmenu = Menu(root,tearoff=False)
# Create a list of three commands in the pop-up menu
popupmenu.add_command(label="Cut",command=cutJob)
popupmenu.add_command(label="Copy",command=copyJob)
popupmenu.add_command(label="Paste",command=pasteJob)
# Click on the right mouse button binding to display the pop-up menu
root.bind("<Button-3>",showPopupMenu)
# create Text
text = Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Five Hundred Miles\n") # Set Tag at the same time when inserting
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")
text.insert(END,"A hundred miles,\n")
root.mainloop()
Output:
The most important for the above program are the following three methods. The following is the cutJob( ) method.
def cutJob(): # Cut method
copyJob() # Copy selected text
text.delete(SEL_FIRST, SEL_LAST) # Delete selected text
When the cut command is executed in the edit function, the data is temporarily stored on the clipboard, so line 5 executes copyJob( ) first, and this method stores the selected text range on the clipboard. Line 6 then deletes the selected text range. The following is the copyJob( ) method.
def copyJob(): # Copy method
try:
text.clipboard_clear() # Clear clipboard
copyText = text.get(SEL_FIRST, SEL_LAST) # Copy selection area
text.clipboard_append(copyText) # Write to clipboard
except TclError:
print("Not selected.")
Copy is to copy the selected data to the clipboard first, and to simplify it, use the clipboard_clear( ) method in line 9 to delete the data from the clipboard first. Since reading the selected block text without selecting the text will cause an exception, the program adds try…except design. Line 10 is to read the selected block of text into the copyText variable. Line 11 then uses the clipboard_append( ) method to write the contents of the parameter copyText variable to the clipboard. The following is the design of the pasteJob( ) method.
def pasteJob(): # paste method
try:
copyText = text.selection_get(selection="CLIPBOARD") # Read clipboard contents
text.insert(INSERT, copyText) # Insert content
except TclError:
print("No data on the clipboard")
If the clipboard does not have data in the execution of the read will generate a TclError exception, so the design adds a try … except design. Line 16 calls selection_get( ) method to read the contents of the clipboard, the contents read will be stored in copyText, line 17 is the contents of the read copyText inserted into the edit area INSERT location.
However, the above Cut/Copy/Paste methods have now been built into tkinter’s virtual events, which can be directly referenced, see the following methods.
Example#2
Using the built-in virtual methods.
from tkinter import *
from tkinter import messagebox
def cutJob(): # Cut method
print("Cut operation in progress...")
text.event_generate("<<Cut>>")
def copyJob():
print("Copy operation in process...")
text.event_generate("<<Copy>>")
def pasteJob():
print("Paste operation is in progress...")
text.event_generate("<<Paste>>")
def showPopupMenu(event):
print("Show pop-up menu...")
popupmenu.post(event.x_root,event.y_root)
root = Tk()
root.title("apidemos.com")
root.geometry("300x180")
popupmenu = Menu(root,tearoff=False)
# Create a list of three commands in the pop-up menu
popupmenu.add_command(label="Cut",command=cutJob)
popupmenu.add_command(label="Copy",command=copyJob)
popupmenu.add_command(label="Paste",command=pasteJob)
# Click on the right mouse button binding to display the pop-up menu
root.bind("<Button-3>",showPopupMenu)
# create Text
text = Text(root)
text.pack(fill=BOTH,expand=True,padx=3,pady=2)
text.insert(END,"Five Hundred Miles\n") # Set Tag at the same time when inserting
text.insert(END,"If you miss the rain I'm on,\n")
text.insert(END,"You will know that I am gone.\n")
text.insert(END,"You can hear the whistle blow\n")
text.insert(END,"A hundred miles,\n")
root.mainloop()
Output: