简体   繁体   English

在尝试粘贴时,使用 tkinter 从 Windows 10 中的 Python 3.4 复制到剪贴板会导致崩溃

[英]Copying to clipboard from Python 3.4 in Windows 10 using tkinter causes crashes when trying to paste

I've tried a number of different things and searched for the topic here, but I can't find a solution to this.我尝试了许多不同的方法并在此处搜索了该主题,但找不到解决方案。 The code runs fine, but when I try to paste what it's copied to the clipboard, the program I'm pasting into stops responding.代码运行良好,但是当我尝试将复制的内容粘贴到剪贴板时,我正在粘贴的程序停止响应。 As soon as I close my Python application, the programs start to respond again, but the clipboard is empty.一旦我关闭我的 Python 应用程序,程序就会再次开始响应,但剪贴板是空的。 This is for a school assignment and it requires me to use only tools that come with the Python installation, so no Pyperclip or the like.这是一个学校作业,它要求我只使用 Python 安装附带的工具,所以没有 Pyperclip 之类的。

Here's the code I'm working from:这是我正在使用的代码:

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()

I use os.system to pipe the text to the clip command.我使用os.system将文本通过管道传送到clip命令。

I was worried this would be insecure at first because a user could input a shell command as the text to be copied into the clipboard, but I realized since this is a calculator program it should have input validation to not accept any non-numerical input anyway so that solves that problem.起初我担心这会不安全,因为用户可以输入一个 shell 命令作为要复制到剪贴板的文本,但我意识到,因为这是一个计算器程序,它应该有输入验证以不接受任何非数字输入这样就解决了这个问题。

def clipboard(text):
    cmd = 'echo | set /p nul=' + str(text) + '| clip'
    os.system(cmd)

You cannot do this with tkinters built in clipboard method.您无法使用内置剪贴板方法的 tkinter 执行此操作。 Tkinter needs to stay active for the clipboard to keep the content. Tkinter 需要保持活动状态,以便剪贴板保留内容。 If you close the instance in the same loop as you are appending to clipboard you will just end up losing whats in the clipboard.如果您在附加到剪贴板的同一循环中关闭实例,您最终将丢失剪贴板中的内容。 At least this is the behavior with Tkinters built in methods.至少这是 Tkinter 内置方法的行为。

You could pip install clipboard and use its methods.您可以pip install clipboard并使用它的方法。 This will keep the content on the clipboard even after Tkinter closes.即使在 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()

Try using pyperclip eg尝试使用 pyperclip 例如

import pyperclip 
pyperclip.copy(“hello”)
#copies hello into the clipboard 

Check out the official pyperclip documentation at https://pyperclip.readthedocs.io/en/latest/introduction.htmlhttps://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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM