self.mrEntry.event_delete(\'<<Paste>>\', \'<Control-v>\')\nself.mrEntry.event_add(\'<Control-v>\', lambda *_: self.handle_clipboard()) # ERROR occurs\n\ndef handle_clipboard(self):\n # Split the clipboard text up by every \'\\n\' and distribute them among the entries\n # In contrast to pasting all the text into one entry\n
Run Code Online (Sandbox Code Playgroud)\n\n是否可以覆盖Control-v
快捷方式,将剪贴板分布在多个条目中,而不是将所有内容粘贴到一个条目中?
从聚焦的条目开始,对于\\n
剪贴板中的每个条目,将其粘贴到后续条目中。
负责剪贴板处理的函数:(它粘贴文本两次,因为我们有一个要粘贴的全局绑定,以及一个对某些选定条目的显式绑定。)
\n\ndef handle_clipboard(self, focused_entry):\n """Function to destribute the clipboard data into seperate entries"""\n\n if \'\\n\' not in root.clipboard_get():\n # If there is only one line in clipboard, paste it all in the focused cell\n return\n\n # count number of lines (cells) there is in the clipboard\n clipboard_cells = (cell for line in root.clipboard_get().split(\'\\n\')[:-1]\n for cell in line.split(\'\\t\'))\n print(clipboard_cells)\n\n # Find corresponding \'key\' for the \'focused entry\'\n for key, entry in self.entries.items():\n if entry == focused_entry:\n break\n\n # We start from the focused cell and insert until there are no more entries\n index = self.n\xc3\xb8gletal.index(key)\n for entry in (self.entries[entry] for entry in self.n\xc3\xb8gletal[index:]):\n\n try:\n n = next(clipboard_cells)\n entry.delete(0, \'end\')\n entry.insert(0, n)\n except StopIteration:\n # There is not more to paste\n # but still more entries to paste in\n pass\n
Run Code Online (Sandbox Code Playgroud)\n
从可用性角度来看,这似乎是一个坏主意,但实现非常简单。您不必使用event_delete
or event_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()
Run Code Online (Sandbox Code Playgroud)