首页 > 解决方案 > 我的图像不会显示,但我的图像的分辨率已应用

问题描述

我正在学习 tkinter 模块,但遇到了问题。我做了一个功能来显示我文件夹中的图像,但我的图像不会显示,但窗口的分辨率与我的图像相同。有人有解决方案吗?

from tkinter import *
from PIL import ImageTk, Image

root = Tk()

def my_image(img, row, column) :
    pic = ImageTk.PhotoImage(Image.open("C:/Users/Mark/Downloads/test/" + img))
    my_img = Label(image=pic)
    return my_img.grid(row=row, column=column)

# Create image
image1 = my_image("luigi_icon.png", 0, 1)

root.mainloop()

标签: pythonpython-3.x

解决方案


这个问题在 Stackoverflow 上出现过很多次。

当将图像分配给局部变量时bugPhotoImage其中会从内存中删除图像。您必须将其分配给全局变量或某个对象

常见的解决方案是将其分配piclabel哪个显示器。

my_img.pic = pic

请参阅Note页面末尾的PhotoImage
(它是存档版本,Wayback Machine因为原始版本已被删除)


顺便提一句:

你还有其他问题。grid()None. my_img如果您想稍后访问标签(即替换图像),您应该返回。

tk.PhotoImage目前可以使用原件,png因此您不需要PIL. 但是,如果您想使用一些不太流行的图像格式,那么您可能需要pillow.


import os
#from tkinter import *
import tkinter as tk  # PEP8: `import *` is not preferred
from PIL import ImageTk, Image

# --- functions ---

def my_image(img, row, column) :
    fullpath = os.path.join("C:/Users/Mark/Downloads/test/", img)

    #pic = ImageTk.PhotoImage(Image.open(fullpath))
    # or
    #pic =  ImageTk.PhotoImage(file=fullpath)
    # or even without `PIL/pillow` for `png`
    pic = tk.PhotoImage(file=fullpath)

    my_img = tk.Label(image=pic)
    my_img.grid(row=row, column=column)

    my_img.pic = pic  # solution for bug in `PhotoImage`

    return my_img

# --- main ---

root = tk.Tk()

image1 = my_image("luigi_icon.png", 0, 1)

root.mainloop()

推荐阅读