python - 如何将图像添加到小部件?为什么不显示图像?

标签 python image tkinter

如何在 tkinter 中将图像添加到小部件?

为什么当我使用这段代码时它不起作用:

some_widget.config(image=PhotoImage(file="test.png"), compound=RIGHT)

但这确实有效吗?

an_image=PhotoImage(file="test.png")
some_widget.config(image=anImage, compound=RIGHT)

最佳答案

当您尝试在第一个版本中使用它时,您的图像正在被垃圾收集。

effbot 很古老,但这里很好 snippet :

You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.

在第二个版本中,图像是在全局级别声明的。

这是另一个演示此问题的示例,您希望它也能正常工作,毕竟它只是函数中的相同代码

不起作用:

import tkinter as tk
from PIL import ImageTk

root = tk.Tk()
def make_button():
    b = tk.Button(root)
    image = ImageTk.PhotoImage(file="1.png")
    b.config(image=image)
    b.pack()
make_button()
root.mainloop()

有效:

import tkiner as tk
from PIL import ImageTk

root = tk.Tk()
def make_button():
    b = tk.Button(root)
    image = ImageTk.PhotoImage(file="1.png")
    b.config(image=image)
    b.image = image
    b.pack()
make_button()
root.mainloop()

为什么? make_button 中的变量是该函数的局部变量。如果您在类里面遇到此类问题,也有同样的想法。

关于python - 如何将图像添加到小部件?为什么不显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515847/

相关文章:

image - 透明像素颜色-Go lang图像

php - 如何在 PHP 中动态调整图像大小

python - matplotlib 图表缩小了 tkinter 窗口

python - MySQL 用空字符串替换 Null

python - BeautifulSoup:如何忽略虚假的结束标签

android - 在运行时向 Activity 背景添加半透明覆盖

python - 默认情况下不检查 Tkinter 单选按钮

python - brew 安装Python/matplotlib不工作: No module named _tkinter

python - Tornado 有正确的请求正文,但找不到正确的参数

python - 打开网页并返回所有链接及其文本的字典的函数