Pasting an image from clipboard in Tkinter?

Eric Brunel see.signature at no.spam
Tue Jun 12 05:24:50 EDT 2007


On Mon, 11 Jun 2007 14:23:48 +0200, exhuma.twn <exhuma at gmail.com> wrote:
> As many might know, windows allows to copy an image into the clipboard
> by pressing the "Print Screen" button on the keyboard. Is it possible
> to paste such an image from the clipboard into a "Text" widget in
> Tkinter? Here is my first attempt with just trying to print out the
> image data:
>
> -----------------
> def pasteImg(tgt):
>    global clipboardEnabled
>    if not clipboardEnabled: return
>
>    win32clipboard.OpenClipboard(0)
>    print win32clipboard.GetClipboardData()
>    win32clipboard.CloseClipboard()
> -----------------
>
> This works fine with selecting text, but comes up with the following
> error when trying to paste an image:
>
> -----------------
> Exception in Tkinter callback
> Traceback (most recent call last):
>   File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
>     return self.func(*args)
>   File "X:\development\testing\tkwiki\tkwiki.py", line 52, in <lambda>
>     Button( root, command=lambda: pasteImg(txt) ).pack()
>   File "X:\development\testing\tkwiki\tkwiki.py", line 38, in pasteImg
>     print win32clipboard.GetClipboardData()
> TypeError: Specified clipboard format is not available
> -----------------
>
> Obviously the clipboard does not know about that format. Does that
> mean I have to wait until it's implemented or are there other ways to
> access the image data?

According to http://msdn2.microsoft.com/en-us/library/ms649039.aspx, there  
is format that you should pass to GetClipboardData telling the data type  
you expect to get. The format you should specify to get a bitmap image is  
named CF_BITMAP in the Windows API. AFAIK, this constant is not exposed in  
the Python world, so you have to pass directly the numeric value, which is  
2.

But even if you do get the clipboard contents, you'll get it in BMP  
format, that tk/Tkinter does not understand by default. So you'll need a  
means to convert it to the only format known to tk/Tkinter by default,  
which is GIF. PIL is certainly able to do that (I don't use it myself);  
you may also rely on an external conversion utility.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"



More information about the Python-list mailing list