覆盖tkinter'ctrl+v'以在多个条目之间拆分粘贴,而不是将其全部粘贴到上

2024-09-30 16:20:26 发布

您现在位置:Python中文网/ 问答频道 /正文

self.mrEntry.event_delete('<<Paste>>', '<Control-v>')
self.mrEntry.event_add('<Control-v>', lambda *_: self.handle_clipboard()) # ERROR occurs

def handle_clipboard(self):
    # Split the clipboard text up by every '\n' and distribute them among the entries
    # In contrast to pasting all the text into one entry

是否可以覆盖Control-v快捷方式,在多个条目之间分发剪贴板,而不是将所有内容粘贴到一个条目中?在

从聚焦的条目开始,对于剪贴板中的每个\n,将其粘贴到后续条目中。在

负责剪贴板处理的函数:(它将文本粘贴两次,因为我们得到了要粘贴的全局绑定,以及显式地绑定到某些选定的条目。)

^{pr2}$

Tags: thelambdatextselfeventadd粘贴条目
1条回答
网友
1楼 · 发布于 2024-09-30 16:20:26

这在可用性方面似乎是个坏主意,但实现非常简单。您不必使用event_deleteevent_add,只需绑定到<<Paste>>事件。在

如果绑定到特殊的catch all "all",那么无论哪个小部件有焦点,都只需执行一个绑定即可工作,不过如果需要,可以只绑定到条目小部件。在

重要的是让您的函数返回字符串"break",这将阻止任何其他事件处理程序处理粘贴事件。在

这里有一个人为的例子:

import tkinter as tk

root = tk.Tk()
text = tk.Text(height=6)
text.pack(side="top", fill="x")

for i in range(10):
    text.insert("end", "this is line #%d\n" % i)

entrys = []
for i in range(10):
    entry = tk.Entry(root)
    entry.pack(side="top", fill="x")
    entrys.append(entry)

def handle_clipboard(event):
    for entry in entrys:
        entry.delete(0, "end")

    lines = root.clipboard_get().split("\n")
    for entry, line in zip(entrys, lines):
        entry.insert(0, line)
    return "break"

root.bind_all("<<Paste>>", handle_clipboard)

root.mainloop()

相关问题 更多 >