Tkinter notes

I keep getting tripped up by the same problems so this note on Tkinter is long overdue.

Most importantly, remember to keep a global reference to all images that you want to have persist on the canvas or tk window. Also, make sure that the ‘global’ reference is called at the beginning of any method using those images. I keep forgetting one or the other and getting stuck over why my images are not appearing. Any images created within a method will not appear unless referenced by a more permanent variable. I need to remember that you cannot just create images on the fly and throw them onto the canvas (although this seems to work for lines and ovals). So:
1) Make sure there is a permanent reference, and
2) Make sure to use ‘global’ or pass the image as an argument for editing.

Another problem I keep encountering is editing PIL images and getting the ImageTk.PhotoImage method to accept an image.
Getting subwindow of image:

subwin = imjpg.copy().crop( (box coordinates) )

You can chain the copy with crop.
im.load():
The load method seems to only give you pixel access to an image for editing, so I think it is not much use since you can’t do slicing. ImageDraw is better for drawing figures.

Masking:

# MAKE COPY IF YOU WANT TO KEEP ORIGINAL.
imcopy = im.copy()
# COLOR: 0 = TRANSPARENT, 255 = OPAQUE.
mask = Image.new('L', imjpg.size, color=100)
# GET A VIEW OF IMAGE FOR DRAWING. EDITING 'DRAW' ALSO CHANGES 'MASK'.
draw = ImageDraw.Draw(mask)
...
# OVERWRITE OR ADD ALPHA LAYER TO IMAGE ('RGB' -> 'RGBA')
imcopy.putalpha(mask)
# SAVE TO GLOBALLY REFERENCED VARIABLE AS A Tk COMPATIBLE IMAGE.
immasked = ImageTk.PhotoImage(imcopy)