1

I'm trying to make a paint app, but i can't seem to open file to canvas.

from tkinter import *
from tkinter import colorchooser
from tkinter import filedialog
import os
import PIL
from PIL import Image, ImageDraw, ImageGrab, ImageTk

file = filedialog.askopenfilename(defaultextension = ".png",
                                      filetypes = [("All Files", "*.*"), ("Image File", ".png")])
if file is None:
    return
else:
    load = Image.open(file)
    render = ImageTk.PhotoImage(load)
    canvas.create_image(700,700, image=render)

Matiiss
  • 5,970
  • 2
  • 12
  • 29
  • There are not `import`s in code you show, though you clearly use non-built-ins (Image, ImageTk), please add relevant `import`s. – Daweo Jun 16 '21 at 09:35
  • next time remember to add the relevant library tag in this case `tkinter` tag to Your question (I already edited it in but remember to do that next time) – Matiiss Jun 16 '21 at 09:44
  • how big is your Canvas? because You add the image at 700, 700 which is pretty far from the top left corner, also I suggest You do this: `if not file:` instead of `if file is None` since it is shorter and covers some more cases also why is there a `return`? – Matiiss Jun 16 '21 at 09:46
  • The canvas size is 700 x 700, and the return is for preventing the exception when closing the open file – adfa adfadfa Jun 16 '21 at 09:52
  • 2 things that may be worth a try: 1. make `render` a global variable so it doesn't get garbage collected and 2. set the coords to (0, 0) and use `anchor="nw"`. I disagree with @Matiiss and think `file is None` is the better way to go (PEP 8 says: "Also, beware of writing `if x` when you really mean `if x is not None`"). – Minion Jim Jun 16 '21 at 09:58
  • 1
    @MinionJim thanks for the PEP8 info (didn't know about that), agreed about that garbage collection which is especially relevant if this is created in a function which this question is related to: [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – Matiiss Jun 16 '21 at 10:01

0 Answers0