Python: copying from clipboard using tkinter without displaying window

*爱你&永不变心* 提交于 2019-11-29 07:37:30

Window is created by tkinter.Tk() (or other elements which need window) not by tk().mainloop(). Mainloop keeps program working.

Maybe try Pyperclip or clipboard

This works fine except a blank tkinter window pops up every time this executes.

You can hide this window:

from tkinter import Tk
root = Tk()
root.withdraw()
number = root.clipboard_get()
DrDurango

I had the same problem. This worked for me on windows 7, python 2.7. I now only get one window.

from Tkinter import *
root = Tk()
cliptext = root.clipboard_get()
lab=Label(root, text = cliptext)
lab.pack()
root.mainloop()
Vengeur69
AnnoyingWindow = Tk()
ClipBoard = AnnoyingWindow.clipboard_get()
AnnoyingWindow.destroy()
print(ClipBoard)

Here's a Python function based on this answer that replaces/returns clipboard text using Tkinter, a built-in Python module, without showing the window.

def use_clipboard(paste_text=None):
    import tkinter # For Python 2, replace with "import Tkinter as tkinter".
    tk = tkinter.Tk()
    tk.withdraw()
    if type(paste_text) == str: # Set clipboard text.
        tk.clipboard_clear()
        tk.clipboard_append(paste_text)
    try:
        clipboard_text = tk.clipboard_get()
    except tkinter.TclError:
        clipboard_text = ''
    r.update() # Stops a few errors (clipboard text unchanged, command line program unresponsive, window not destroyed).
    tk.destroy()
    return clipboard_text

A small disadvantage with using this Tkinter based method is that it uses a quickly hidden window which isn't ideal but this shouldn't be noticeable.
This answer uses content from my original answer on the Stack Overflow question How to copy/get an image in the clipboard with Python (I accept Tkinter for text).

maviz

You actually do it without tkinter and in a much more simple way:

import pyperclip

clipboard_content = pyperclip.paste()
Darth Futuza
number.withdraw() #this hides the ui for the object

Just add this command at the beginning when you create your TKinter object and it will hide the UI. See this similar question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!