Tkinter copy to clipboard not working in PyCharm Tkinter copy to clipboard not working in PyCharm tkinter tkinter

Tkinter copy to clipboard not working in PyCharm


There seems to be problem if the clipboard is manipulated and the program closes too quickly soon after. The following program worked for me but was unreliable when the call to root.after only used one millisecond for the delay. Other possibilities were tried, but code down below should work:

import randomimport stringimport tkinterdef main():    root = tkinter.Tk()    root.after_idle(run_code, root)    root.after(100, root.destroy)    root.mainloop()def run_code(root):    root.withdraw()    root.clipboard_clear()    root.clipboard_append(''.join(random.sample(string.ascii_letters, 10)))    print('Clipboard is ready.')if __name__ == '__main__':    main()

The following is a mildly more useful version of the program and demonstrates that you can make many calls to root.after_idle to run your code in a sequential manner. Its design is primarily for use to process command-line arguments and send them to your clipboard for you:

import sysimport tkinterdef main(argv):    root = tkinter.Tk()    root.after_idle(root.withdraw)    root.after_idle(root.clipboard_clear)    root.after_idle(root.clipboard_append, ' '.join(argv[1:]))    root.after_idle(print, 'The clipboard is ready.')    root.after(100, root.destroy)    root.mainloop()    return 0if __name__ == '__main__':    sys.exit(main(sys.argv))