Advertisement
here2share

### Tk_copy_from_canvas.py

Jun 15th, 2015
367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.66 KB | None | 0 0
  1. ### Tk_copy_from_canvas.py
  2.  
  3. import sys
  4. import tkMessageBox as tkm
  5. from PIL import Image            # Only if you need and use the PIL library.
  6.  
  7. if sys.platform.startswith('win'):
  8.     # Image grab comes from PIL (Python Imaging Library)
  9.     from PIL import ImageGrab
  10.     # We use wx to copy to the clipboard on windows machines.  The PySimpleApp line initializes wx.  There does not appear to be
  11.     # a conflict between wx started this way and Tk.  Note that if you don't want the copy to clipboard or read from clipboard capability,
  12.     # you can just delete the two lines below (and all the associated wx routines).
  13.     import wx
  14.     app = wx.PySimpleApp()
  15.  
  16. def grab_image(widget=None, bbox=None, offset1=2, offset2=2):
  17.     # widget = the Tk widget to copy to the clipboard
  18.     # bbox = the bounding box containing the area to copy to the clipboard.  Should be a tuple of 4 integers.
  19.     # either widget or bbox must not be None.  If both are not None, widget is used.
  20.     # Note that if widget is used, the screen will be updated.  It can't do that if only bbox is used, so that should be done by the caller
  21.     # offset1 & offset2 determine the amount to expand the box beyond the widget in order to make sure the whole widget is captured
  22.     # they are used because some widgets (such as canvases) appear to be a bit wonky in whether borders are copied or not
  23.     im = ""
  24.     if widget:
  25.         # The guts of this routine were originally provided by Fredrik Lundh
  26.         widget.update()
  27.         x0 = widget.winfo_rootx()
  28.         y0 = widget.winfo_rooty()
  29.         x1 = x0 + widget.winfo_width()
  30.         y1 = y0 + widget.winfo_height()
  31.         im = ImageGrab.grab((x0-offset1, y0-offset1, x1+offset2, y1+offset2))
  32.     elif bbox:
  33.         im = ImageGrab.grab(bbox)
  34.     return im
  35.  
  36. def copy_to_clipboard(**keyw):
  37.     # Copies an image of a widget or screen area to the clipboard.
  38.     #
  39.     # Any arguments to this routine are passed directly to grab_image, so see that routine for possible useful arguments
  40.     # In particular, either widget or bbox must be supplied by the user
  41.     #
  42.     if sys.platform.startswith('win'):
  43.         im = grab_image(**keyw)
  44.         if im:
  45.             bitmap = pil_to_bitmap(im)
  46.             clipboard_bitmap = wx.BitmapDataObject(bitmap)
  47.             if wx.TheClipboard.Open():
  48.                 wx.TheClipboard.SetData(clipboard_bitmap)
  49.                 wx.TheClipboard.Close()
  50.     else:
  51.         tkm.showerror('Clipboard Copy Error', 'Clipboard copy not implemented on this platform')
  52.  
  53. def copy_to_file(filename, **keyw):
  54.     # Copies an image of a widget or screen area to a file.  The file type can be any that the Python Imaging Library supports, and the
  55.     # file type is determined by the extension of filename.
  56.     #
  57.     # filename = name of file to save the image to.  The file name extension is used to determine the image type.
  58.     #
  59.     # Any arguments to this routine are passed directly to grab_image, so see that routine for possible useful arguments
  60.     # In particular, either widget= or bbox= must be supplied by the user
  61.     #
  62.     if sys.platform.startswith('win'):
  63.         im = grab_image(**keyw)
  64.         if im:
  65.             im.save(directory+filename)
  66.             tkm.showinfo('Image Copied', 'image copied to '+directory+' as '+filename)
  67.     else:
  68.         tkm.showerror('Image Grab Error', 'Image grab not implemented on this platform')
  69.  
  70. def get_bitmap_from_clipboard():
  71.     # Returns a PIL image from the clipboard, which should have bitmap data in it
  72.     # The PIL image can be used in Tk widgets by converting it using ImageTk.PhotoImage(PIL image)
  73.     bm = wx.BitmapDataObject()
  74.     if wx.TheClipboard.GetData(bm):
  75.         wxbmp = bm.GetBitmap()
  76.         try:
  77.             pilimage = bitmap_to_pil(wxbmp)
  78.             return pilimage
  79.         except:
  80.             tkm.showerror('Clipboard Paste Error', 'Clipboard bitmap data could not be converted to an image')
  81.             return False
  82.     else:
  83.         tkm.showerror('Clipboard Paste Error', 'Clipboard data is not a recognized bitmap format')
  84.         return False
  85.  
  86. ########################################
  87. # Start of routines taken from http://wiki.wxpython.org/index.cgi/WorkingWithImages
  88. ########################################
  89. def bitmap_to_pil(bitmap):
  90.     return wximage_to_pil(bitmap_to_wximage(bitmap))
  91.  
  92. def bitmap_to_wximage(bitmap):
  93.     return wx.ImageFromBitmap(bitmap)
  94.  
  95. def pil_to_bitmap(pil):
  96.     return wximage_to_bitmap(pil_to_wximage(pil))
  97.  
  98. def pil_to_wximage(pil):
  99.     image = wx.EmptyImage(pil.size[0], pil.size[1])
  100.     image.SetData(pil.convert('RGB').tostring())
  101.     return image
  102.  
  103. #Or, if you want to copy alpha channels too (available from wxPython 2.5)
  104. def piltoimage(pil,alpha=True):
  105.    if alpha:
  106.        image = apply( wx.EmptyImage, pil.size )
  107.        image.SetData( pil.convert( "RGB").tostring() )
  108.        image.SetAlphaData(pil.convert("RGBA").tostring()[3::4])
  109.    else:
  110.        image = wx.EmptyImage(pil.size[0], pil.size[1])
  111.        new_image = pil.convert('RGB')
  112.        data = new_image.tostring()
  113.        image.SetData(data)
  114.    return image
  115.  
  116. def wximage_to_pil(image):
  117.     pil = Image.new('RGB', (image.GetWidth(), image.GetHeight()))
  118.     pil.fromstring(image.GetData())
  119.     return pil
  120.  
  121. def wximage_to_bitmap(image):
  122.     return image.ConvertToBitmap()
  123.  
  124. ########################################
  125. # End of routines taken from http://wiki.wxpython.org/index.cgi/WorkingWithImages
  126. ########################################
  127.  
  128. if __name__ == '__main__':
  129.  
  130.     directory = 'C:\\Users\\test\\'
  131.  
  132.     def copy_canvas():
  133.         copy_to_clipboard(widget=canvas)
  134.     def copy_canvas_file():
  135.         copy_to_file('testimage.jpg', widget=canvas)
  136.     print 'testing'
  137.     from Tkinter import *
  138.     root = Tk()
  139.     canvas = Canvas(root, bg='white')
  140.    
  141.     root.title("Copy From Canvas")
  142.  
  143.     def star_5pt(x,y,s):
  144.         a,b,c,d,e,f,g,h,j,k,m,n,p = 0,180,294,476,250,192,308,500,340,402,357,96,157
  145.         plot_xy = [(a,b),(f,b),(e,a),(g,b),(h,b),(j,c),(k,d),(e,m),(n,d),(p,c)]
  146.         nova=[]
  147.         for xy in plot_xy:
  148.             xy = (xy[0]*0.002)*s+x,(xy[1]*0.002)*s+y
  149.             nova.append(xy)
  150.         return nova
  151.  
  152.     star = star_5pt(30,60,200)
  153.  
  154.     canvas.create_rectangle(20, 100, 320, 200, fill='darkgrey', width=0)
  155.     canvas.create_polygon((star), outline='purple', width=10, fill='yellow')
  156.     canvas.create_arc(30, 20, 360, 400, start=0, extent=90, outline='orange', fill="orange", style='chord')
  157.     canvas.create_oval(150, 50, 180, 150, fill='red')
  158.     canvas.create_line(10, 10, 100, 120, width=4, fill='grey')
  159.     canvas.create_arc(200, 180, 300, 250, start=0, extent=270, fill="cyan") ### pieslice instead of arc ???
  160.     canvas.create_text(195,90,fill="darkgreen",font="Courier 60 italic bold",text="Hi!\n    ABC")
  161.     canvas.create_arc(45, 45, 210, 210, start=-45, extent=-180, outline="white", style='arc')
  162.     canvas.create_arc(50, 50, 205, 205, start=0, extent=-180, style='arc')
  163.     canvas.pack(side=TOP, padx=5, pady=5)
  164.     b1 = Button(root,text='copy to clipboard', command=copy_canvas).pack(side=LEFT, padx=5, pady=5)
  165.     b2 = Button(root,text='copy to testimage.jpg', command=copy_canvas_file).pack(side=RIGHT, padx=5, pady=5)
  166.     root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement