python - 我的图像不会显示,但我的图像的分辨率已应用
问题描述
我正在学习 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()
解决方案
这个问题在 Stackoverflow 上出现过很多次。
当将图像分配给局部变量时bug
,PhotoImage
其中会从内存中删除图像。您必须将其分配给全局变量或某个对象
常见的解决方案是将其分配pic
给label
哪个显示器。
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()
推荐阅读
- java - java.lang.ClassCastException:java.math.BigDecimal 不能转换为 java.lang.Long
- botframework - 在虚拟助手模板中使用 Content Moderator 会引发错误
- java - 在 Java 8 中以静态方式获取类名
- javascript - 注释掉正则表达式,javascript
- java - 如何使用 Apache Olingo V2 实现分页?
- r - R比较/标志/天差/跳过相同的交易行
- php - 如何修复 PHP 和 MySQL 中的注释部分?
- c# - 没有得到正确的输出
- git - 从FB分支后,获取GitHub PR只显示FB和master的区别
- python - 如何让硒等待多个元素加载