tkinter PhotoImage doesn't exist?

前端 未结 2 320
栀梦
栀梦 2021-01-20 03:49
from tkinter import *

root = Tk()

photo = PhotoImage(file=\'blueface.png\')
label = Label(root, image=photo)
label.pack()

root.mainloop()

The im

相关标签:
2条回答
  • 2021-01-20 04:30

    Older versions of tkinter can not handle .png's that well. Try making the file a .gif. Or use the PhotoImage from PIL:

    import tkinter as tk
    from PIL import Image, ImageTk
    
    root = tk.Tk()
    
    photo = ImageTk.PhotoImage(Image.open('blueface.png'))
    label = tk.Label(root, image=photo)
    label.pack()
    
    root.mainloop()
    
    0 讨论(0)
  • 2021-01-20 04:38

    It doesn't matter very much that the image is in the same folder as the script, when you call the file like that without a path python assumes it's in the same folder that you were working on when you started the script. For example, if both the script and the image are in temp folder, and you started your script like this:

    python temp/script.py
    

    The interpreter doesn't realize that blueface.png is also in temp and looks for it in the folder that you were in, in this case the parent of temp

    What you should do, is either use absolute paths, or use the __file__ to get the full script address first. For example:

    photo = PhotoImage(file='/absolute/path/to/image/blueface.png')
    

    Or using the current script's location to build the image's path:

    import os
    base_folder = os.path.dirname(__file__)
    image_path = os.path.join(base_folder, 'blueface.png')
    photo = PhotoImage(file=image_path)
    
    0 讨论(0)
提交回复
热议问题