Pastebin
API
tools
faq
paste
Login
Sign up
Please fix the following errors:
New Paste
Syntax Highlighting
### Tk_copy_from_canvas.py import sys import tkMessageBox as tkm from PIL import Image # Only if you need and use the PIL library. if sys.platform.startswith('win'): # Image grab comes from PIL (Python Imaging Library) from PIL import ImageGrab # We use wx to copy to the clipboard on windows machines. The PySimpleApp line initializes wx. There does not appear to be # 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, # you can just delete the two lines below (and all the associated wx routines). import wx app = wx.PySimpleApp() def grab_image(widget=None, bbox=None, offset1=2, offset2=2): # widget = the Tk widget to copy to the clipboard # bbox = the bounding box containing the area to copy to the clipboard. Should be a tuple of 4 integers. # either widget or bbox must not be None. If both are not None, widget is used. # 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 # offset1 & offset2 determine the amount to expand the box beyond the widget in order to make sure the whole widget is captured # they are used because some widgets (such as canvases) appear to be a bit wonky in whether borders are copied or not im = "" if widget: # The guts of this routine were originally provided by Fredrik Lundh widget.update() x0 = widget.winfo_rootx() y0 = widget.winfo_rooty() x1 = x0 + widget.winfo_width() y1 = y0 + widget.winfo_height() im = ImageGrab.grab((x0-offset1, y0-offset1, x1+offset2, y1+offset2)) elif bbox: im = ImageGrab.grab(bbox) return im def copy_to_clipboard(**keyw): # Copies an image of a widget or screen area to the clipboard. # # Any arguments to this routine are passed directly to grab_image, so see that routine for possible useful arguments # In particular, either widget or bbox must be supplied by the user # if sys.platform.startswith('win'): im = grab_image(**keyw) if im: bitmap = pil_to_bitmap(im) clipboard_bitmap = wx.BitmapDataObject(bitmap) if wx.TheClipboard.Open(): wx.TheClipboard.SetData(clipboard_bitmap) wx.TheClipboard.Close() else: tkm.showerror('Clipboard Copy Error', 'Clipboard copy not implemented on this platform') def copy_to_file(filename, **keyw): # 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 # file type is determined by the extension of filename. # # filename = name of file to save the image to. The file name extension is used to determine the image type. # # Any arguments to this routine are passed directly to grab_image, so see that routine for possible useful arguments # In particular, either widget= or bbox= must be supplied by the user # if sys.platform.startswith('win'): im = grab_image(**keyw) if im: im.save(directory+filename) tkm.showinfo('Image Copied', 'image copied to '+directory+' as '+filename) else: tkm.showerror('Image Grab Error', 'Image grab not implemented on this platform') def get_bitmap_from_clipboard(): # Returns a PIL image from the clipboard, which should have bitmap data in it # The PIL image can be used in Tk widgets by converting it using ImageTk.PhotoImage(PIL image) bm = wx.BitmapDataObject() if wx.TheClipboard.GetData(bm): wxbmp = bm.GetBitmap() try: pilimage = bitmap_to_pil(wxbmp) return pilimage except: tkm.showerror('Clipboard Paste Error', 'Clipboard bitmap data could not be converted to an image') return False else: tkm.showerror('Clipboard Paste Error', 'Clipboard data is not a recognized bitmap format') return False ######################################## # Start of routines taken from http://wiki.wxpython.org/index.cgi/WorkingWithImages ######################################## def bitmap_to_pil(bitmap): return wximage_to_pil(bitmap_to_wximage(bitmap)) def bitmap_to_wximage(bitmap): return wx.ImageFromBitmap(bitmap) def pil_to_bitmap(pil): return wximage_to_bitmap(pil_to_wximage(pil)) def pil_to_wximage(pil): image = wx.EmptyImage(pil.size[0], pil.size[1]) image.SetData(pil.convert('RGB').tostring()) return image #Or, if you want to copy alpha channels too (available from wxPython 2.5) def piltoimage(pil,alpha=True): if alpha: image = apply( wx.EmptyImage, pil.size ) image.SetData( pil.convert( "RGB").tostring() ) image.SetAlphaData(pil.convert("RGBA").tostring()[3::4]) else: image = wx.EmptyImage(pil.size[0], pil.size[1]) new_image = pil.convert('RGB') data = new_image.tostring() image.SetData(data) return image def wximage_to_pil(image): pil = Image.new('RGB', (image.GetWidth(), image.GetHeight())) pil.fromstring(image.GetData()) return pil def wximage_to_bitmap(image): return image.ConvertToBitmap() ######################################## # End of routines taken from http://wiki.wxpython.org/index.cgi/WorkingWithImages ######################################## if __name__ == '__main__': directory = 'C:\\Users\\test\\' def copy_canvas(): copy_to_clipboard(widget=canvas) def copy_canvas_file(): copy_to_file('testimage.jpg', widget=canvas) print 'testing' from Tkinter import * root = Tk() canvas = Canvas(root, bg='white') root.title("Copy From Canvas") def star_5pt(x,y,s): 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 plot_xy = [(a,b),(f,b),(e,a),(g,b),(h,b),(j,c),(k,d),(e,m),(n,d),(p,c)] nova=[] for xy in plot_xy: xy = (xy[0]*0.002)*s+x,(xy[1]*0.002)*s+y nova.append(xy) return nova star = star_5pt(30,60,200) canvas.create_rectangle(20, 100, 320, 200, fill='darkgrey', width=0) canvas.create_polygon((star), outline='purple', width=10, fill='yellow') canvas.create_arc(30, 20, 360, 400, start=0, extent=90, outline='orange', fill="orange", style='chord') canvas.create_oval(150, 50, 180, 150, fill='red') canvas.create_line(10, 10, 100, 120, width=4, fill='grey') canvas.create_arc(200, 180, 300, 250, start=0, extent=270, fill="cyan") ### pieslice instead of arc ??? canvas.create_text(195,90,fill="darkgreen",font="Courier 60 italic bold",text="Hi!\n ABC") canvas.create_arc(45, 45, 210, 210, start=-45, extent=-180, outline="white", style='arc') canvas.create_arc(50, 50, 205, 205, start=0, extent=-180, style='arc') canvas.pack(side=TOP, padx=5, pady=5) b1 = Button(root,text='copy to clipboard', command=copy_canvas).pack(side=LEFT, padx=5, pady=5) b2 = Button(root,text='copy to testimage.jpg', command=copy_canvas_file).pack(side=RIGHT, padx=5, pady=5) root.mainloop()
Optional Paste Settings
Category:
None
Cryptocurrency
Cybersecurity
Fixit
Food
Gaming
Haiku
Help
History
Housing
Jokes
Legal
Money
Movies
Music
Pets
Photo
Science
Software
Source Code
Spirit
Sports
Travel
TV
Writing
Tags:
Syntax Highlighting:
None
Bash
C
C#
C++
CSS
HTML
JSON
Java
JavaScript
Lua
Markdown (PRO members only)
Objective C
PHP
Perl
Python
Ruby
Swift
4CS
6502 ACME Cross Assembler
6502 Kick Assembler
6502 TASM/64TASS
ABAP
AIMMS
ALGOL 68
APT Sources
ARM
ASM (NASM)
ASP
ActionScript
ActionScript 3
Ada
Apache Log
AppleScript
Arduino
Asymptote
AutoIt
Autohotkey
Avisynth
Awk
BASCOM AVR
BNF
BOO
Bash
Basic4GL
Batch
BibTeX
Blitz Basic
Blitz3D
BlitzMax
BrainFuck
C
C (WinAPI)
C Intermediate Language
C for Macs
C#
C++
C++ (WinAPI)
C++ (with Qt extensions)
C: Loadrunner
CAD DCL
CAD Lisp
CFDG
CMake
COBOL
CSS
Ceylon
ChaiScript
Chapel
Clojure
Clone C
Clone C++
CoffeeScript
ColdFusion
Cuesheet
D
DCL
DCPU-16
DCS
DIV
DOT
Dart
Delphi
Delphi Prism (Oxygene)
Diff
E
ECMAScript
EPC
Easytrieve
Eiffel
Email
Erlang
Euphoria
F#
FO Language
Falcon
Filemaker
Formula One
Fortran
FreeBasic
FreeSWITCH
GAMBAS
GDB
GDScript
Game Maker
Genero
Genie
GetText
Go
Godot GLSL
Groovy
GwBasic
HQ9 Plus
HTML
HTML 5
Haskell
Haxe
HicEst
IDL
INI file
INTERCAL
IO
ISPF Panel Definition
Icon
Inno Script
J
JCL
JSON
Java
Java 5
JavaScript
Julia
KSP (Kontakt Script)
KiXtart
Kotlin
LDIF
LLVM
LOL Code
LScript
Latex
Liberty BASIC
Linden Scripting
Lisp
Loco Basic
Logtalk
Lotus Formulas
Lotus Script
Lua
M68000 Assembler
MIX Assembler
MK-61/52
MPASM
MXML
MagikSF
Make
MapBasic
Markdown (PRO members only)
MatLab
Mercury
MetaPost
Modula 2
Modula 3
Motorola 68000 HiSoft Dev
MySQL
Nagios
NetRexx
Nginx
Nim
NullSoft Installer
OCaml
OCaml Brief
Oberon 2
Objeck Programming Langua
Objective C
Octave
Open Object Rexx
OpenBSD PACKET FILTER
OpenGL Shading
Openoffice BASIC
Oracle 11
Oracle 8
Oz
PARI/GP
PCRE
PHP
PHP Brief
PL/I
PL/SQL
POV-Ray
ParaSail
Pascal
Pawn
Per
Perl
Perl 6
Phix
Pic 16
Pike
Pixel Bender
PostScript
PostgreSQL
PowerBuilder
PowerShell
ProFTPd
Progress
Prolog
Properties
ProvideX
Puppet
PureBasic
PyCon
Python
Python for S60
QBasic
QML
R
RBScript
REBOL
REG
RPM Spec
Racket
Rails
Rexx
Robots
Roff Manpage
Ruby
Ruby Gnuplot
Rust
SAS
SCL
SPARK
SPARQL
SQF
SQL
SSH Config
Scala
Scheme
Scilab
SdlBasic
Smalltalk
Smarty
StandardML
StoneScript
SuperCollider
Swift
SystemVerilog
T-SQL
TCL
TeXgraph
Tera Term
TypeScript
TypoScript
UPC
Unicon
UnrealScript
Urbi
VB.NET
VBScript
VHDL
VIM
Vala
Vedit
VeriLog
Visual Pro Log
VisualBasic
VisualFoxPro
WHOIS
WhiteSpace
Winbatch
XBasic
XML
XPP
Xojo
Xorg Config
YAML
YARA
Z80 Assembler
ZXBasic
autoconf
jQuery
mIRC
newLISP
q/kdb+
thinBasic
Paste Expiration:
Never
Burn after read
10 Minutes
1 Hour
1 Day
1 Week
2 Weeks
1 Month
6 Months
1 Year
Paste Exposure:
Public
Unlisted
Private
Folder:
(members only)
Password
NEW
Enabled
Disabled
Burn after read
NEW
Paste Name / Title:
Create New Paste
Hello
Guest
Sign Up
or
Login
Sign in with Facebook
Sign in with Twitter
Sign in with Google
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login
Public Pastes
+12,000$ in 2 days
CSS | 28 min ago | 0.72 KB
Crypto admin access
29 min ago | 0.43 KB
Free Crypto Method
CSS | 29 min ago | 0.72 KB
Documents
30 min ago | 0.43 KB
Untitled
14 hours ago | 0.68 KB
The Road Not Taken
1 day ago | 0.79 KB
OG OLDHAM CODE
3 days ago | 27.75 KB
remove current bid and bid now button from au...
PHP | 4 days ago | 0.80 KB
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the
Cookies Policy
.
OK, I Understand
Not a member of Pastebin yet?
Sign Up
, it unlocks many cool features!