[英]Copying to clipboard from Python 3.4 in Windows 10 using tkinter causes crashes when trying to paste
我尝试了许多不同的方法并在此处搜索了该主题,但找不到解决方案。 代码运行良好,但是当我尝试将复制的内容粘贴到剪贴板时,我正在粘贴的程序停止响应。 一旦我关闭我的 Python 应用程序,程序就会再次开始响应,但剪贴板是空的。 这是一个学校作业,它要求我只使用 Python 安装附带的工具,所以没有 Pyperclip 之类的。
这是我正在使用的代码:
from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('This is a test to try to copy to clipboard')
r.update()
r.destroy()
您无法使用内置剪贴板方法的 tkinter 执行此操作。 Tkinter 需要保持活动状态,以便剪贴板保留内容。 如果您在附加到剪贴板的同一循环中关闭实例,您最终将丢失剪贴板中的内容。 至少这是 Tkinter 内置方法的行为。
您可以pip install clipboard
并使用它的方法。 即使在 Tkinter 关闭后,这也会将内容保留在剪贴板上。
from tkinter import Tk
import clipboard as cb
r = Tk()
r.withdraw()
cb.copy('This is a test to try to copy to clipboard')
r.destroy()
尝试使用 pyperclip 例如
import pyperclip
pyperclip.copy(“hello”)
#copies hello into the clipboard
在https://pyperclip.readthedocs.io/en/latest/introduction.html查看官方 pyperclip 文档
class main ( ):
def __init__(self, parent):
#super ( ).__init__()
self.menu = tk.Menu ( parent, tearoff = 0,
postcommand = self.enable_selection )
self.menu.add_command ( label = 'Cut', command = self.cut_text )
self.menu.add_command ( label = 'Copy', command = self.copy_text )
self.menu.add_command ( label = 'Paste', command = self.paste_text )
self.menu.add_command ( label = 'Delete', command = self.delete_text )
self.text = tk.Text ( height = 10, width = 50 )
self.text.bind ( '<Button-3>', self.show_popup )
self.text.pack ()
mainloop ()
def enable_selection ( self ):
self.state_clipboard = tk.ACTIVE
if self.text.tag_ranges (tk.SEL):
self.state_selection = tk.ACTIVE
else:
self.state_selection = tk.DISABLED
try:
self.text.selection_get ()
except tk.TclError as e:
pass
#print ( e )
#self.state_clipboard = tk.DISABLED
#self.menu.entryconfig ( 0, state = self.state_selection )
#self.menu.entryconfig ( 1, state = self.state_selection )
#self.menu.entryconfig ( 2, state = self.state_clipboard )
#self.menu.entryconfig ( 3, state = self.state_selection )
def cut_text ( self ):
self.copy_text ()
self.delete_text ()
def copy_text ( self ):
selection = self.text.tag_ranges ( tk.SEL )
if selection:
self.text.clipboard_clear ()
self.text.clipboard_append ( self.text.get (*selection) )
def paste_text ( self ):
try:
self.text.insert ( tk.INSERT, self.text.clipboard_get () )
except tk.TclError:
pass
def delete_text ( self ):
selection = self.text.tag_ranges ( tk.SEL )
if selection:
self.text.delete ( *selection )
def show_popup ( self, event ):
self.menu.post ( event.x_root, event.y_root )
if __name__ == '__main__':
app = main ( tk.Tk() )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.