简体   繁体   中英

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. 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.

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.

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.

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 needs to stay active for the clipboard to keep the content. 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.

You could pip install clipboard and use its methods. This will keep the content on the clipboard even after Tkinter closes.

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

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

Check out the official pyperclip documentation at https://pyperclip.readthedocs.io/en/latest/introduction.html

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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