Python Tkinter 文本框右键复制粘贴功能实现教程
在 Python 中使用 Tkinter 库实现文本框内容的右键复制和粘贴功能,可以通过以下步骤实现:
- 创建一个文本框,使用
Text类实现:
from tkinter import *
root = Tk()
text = Text(root)
text.pack()
root.mainloop()
- 实现右键菜单的功能,使用
Menu类和add_cascade方法实现:
from tkinter import *
def popupmenu(event):
menu.post(event.x_root, event.y_root)
root = Tk()
text = Text(root)
text.pack()
menu = Menu(root, tearoff=0)
menu.add_command(label='复制')
menu.add_command(label='粘贴')
text.bind('<Button-3>', popupmenu)
root.mainloop()
- 实现复制和粘贴的功能,使用
Text类的get和insert方法实现:
from tkinter import *
def popupmenu(event):
menu.post(event.x_root, event.y_root)
def copy():
text.clipboard_clear()
text.clipboard_append(text.selection_get())
def paste():
text.insert(INSERT, text.clipboard_get())
root = Tk()
text = Text(root)
text.pack()
menu = Menu(root, tearoff=0)
menu.add_command(label='复制', command=copy)
menu.add_command(label='粘贴', command=paste)
text.bind('<Button-3>', popupmenu)
root.mainloop()
完整代码如下:
from tkinter import *
def popupmenu(event):
menu.post(event.x_root, event.y_root)
def copy():
text.clipboard_clear()
text.clipboard_append(text.selection_get())
def paste():
text.insert(INSERT, text.clipboard_get())
root = Tk()
text = Text(root)
text.pack()
menu = Menu(root, tearoff=0)
menu.add_command(label='复制', command=copy)
menu.add_command(label='粘贴', command=paste)
text.bind('<Button-3>', popupmenu)
root.mainloop()
原文地址: https://www.cveoy.top/t/topic/lMKN 著作权归作者所有。请勿转载和采集!