如何将图像添加到窗口小部件?为什么图像不显示? [英] How to add an Image to a widget? Why is the image not displayed?

查看:143
本文介绍了如何将图像添加到窗口小部件?为什么图像不显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将图像添加到tkinter中的窗口小部件?

How can I add an image to a widget in tkinter?

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

Why when I use this code it does not work:

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

但是这确实有效吗?:

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


推荐答案

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

Your image is getting garbage collected when you try to use it in the first version.

effbot很古老,但这里是好代码段

effbot is ancient, but here's good snippet:


您必须在Python程序中保留对图像对象的引用,方法是将其存储在全局变量中,或者将其附加到另一个对象。

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.

在第二个版本中,图像在全球范围内声明。

In the second version the image is declared at the global level.

这里'另一个可以证明这个问题的例子,你希望它也可以工作,毕竟它只是在函数中的相同代码

Here's another example that would demonstrate this issue, that you would expect to also work, after all it's the same code just in a function

不起作用:

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 中的变量是该函数的本地变量。如果你在一个类中遇到这种类型的问题,同样的想法。

Why? The variables in make_button are local to that function. Same idea if you run into this type of problem inside a class.

这篇关于如何将图像添加到窗口小部件?为什么图像不显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆