tkinter按钮不显示图像 [英] tkinter button not showing image

查看:380
本文介绍了tkinter按钮不显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像作为背景放在我的一个按钮上,我已经在主窗口中的许多其他按钮上完成了此操作,但是此特定按钮位于顶层窗口中,而图像却没有像它应该加载一样,有人知道为什么吗? (我也尝试过定义按钮的宽度和高度,但这仍然不显示图像)

Hi i am trying to put an image as the background on one of my buttons, i have already done this on lots of other buttons in my main window but this particular button sits inside a top level window and the image doesn't load like it should, does anyone know why? (i have also tried defining the width and height of the button but that still doesn't show the image)

def rec_window():
    recw = Toplevel(width=500,height=500)
    recw.title('Record To.....')
    img1 = PhotoImage(file="C:/Users/Josh Bailey/Desktop/pi_dmx/Gif/mainmenu.gif")
    Button(recw, image=img1, command=rec_preset_1).grid(row=1, column=1)
    Button(recw, text="Preset 2", bg = 'grey70',width=40, height=12,command=rec_preset_2).grid(row=1, column=2)
    Button(recw, text="Preset 3", bg = 'grey70',width=40, height=12,command=rec_preset_3).grid(row=2, column=1)
    Button(recw, text="Preset 4", bg = 'grey70',width=40, height=12,command=rec_preset_4).grid(row=2, column=2)
    Button(recw, text="Cancel", bg='grey70', width=20, height=6, command=recw.destroy). grid(row=3,column=1,columnspan=2, pady=30)

推荐答案

根据程序其余部分的结构,图像可能会被垃圾收集清除:

Depending on how the rest of your program is structured, your image might be getting cleared by garbage-collection:

来自 http://effbot.org/tkinterbook/photoimage.htm

注意:当PhotoImage对象被Python垃圾收集时(例如 当您从将图像存储在本地的函数返回时 变量),即使图像已被显示,图像也会被清除 Tkinter小部件.

Note: When a PhotoImage object is garbage-collected by Python (e.g. when you return from a function which stored an image in a local variable), the image is cleared even if it’s being displayed by a Tkinter widget.

为避免这种情况,程序必须保留对图像的额外引用 目的.一种简单的方法是将图像分配给小部件 属性,如下所示:

To avoid this, the program must keep an extra reference to the image object. A simple way to do this is to assign the image to a widget attribute, like this:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

对于您来说,可以通过将img1声明为全局变量来保留引用来启动函数:

In your case, you can start your function by declaring img1 as a global variable to retain a reference:

global img1

或者,如果您的程序中其他位置已经有img1:

or, if you already have img1 elsewhere in your program:

img1 = PhotoImage(file="C:/Users/Josh Bailey/Desktop/pi_dmx/Gif/mainmenu.gif")
img1Btn = Button(recw, image=img1, command=rec_preset_1)
img1Btn.image = img1
img1Btn.grid(row=1, column=1)

这篇关于tkinter按钮不显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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