Python Tkinter 2.7问题与图像。 [英] Python Tkinter 2.7 Issue with image.

查看:118
本文介绍了Python Tkinter 2.7问题与图像。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在窗口中显示图像....看起来简单够吧?

I am trying to display an image in a window.... seems simple enough right? Well I have a big bug!

我在一个文件中有这个EXACT相同的代码:

I have this EXACT same code in one file:

import Tkinter

root = Tkinter.Tk()
canvas = Tkinter.Canvas(root)
canvas.grid(row = 0, column = 0)
photo = Tkinter.PhotoImage(file = '/Users/Richy/Desktop/1.gif')
image1 = canvas.create_image(0,0, image=photo)
root.mainloop()

它可以工作。

我有一个更大的文件的一部分:

I have this in part of a bigger file:

def officialPictureWindow(self):
    t = Toplevel(self)
    t.wm_title("Official Image")
    self.__canvas3 = Canvas(t)
    self.__canvas3.grid(row = 0, column = 0)
    photo = PhotoImage(file = '/Users/Richy/Desktop/1.gif')
    image1 = self.__canvas3.create_image(0,0, image=photo)

它不工作!

当有人按菜单栏上的按钮时,调用该函数。所有其他菜单按钮我操作正常,并显示他们的窗口。在其他人没有图像。

That function is called when someone presses a button on a menubar I have. All the other menubar buttons I have operate properly and show their windows. There's no images in the others though.

这没有任何错误。

推荐答案

您需要额外参考 photo ,所以它不会在函数结束时过早地收集垃圾。 Tkinter简介进一步解释:

You need to keep an additional reference to photo so it doesn't get prematurely garbage collected at the end of the function. An Introduction to Tkinter explains further:


注意:当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.

为了避免这种情况,程序必须保留对图像对象的额外引用。一个简单的方法是将图像分配给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) code>

label.image = photo#保留参考!

标签。 pack()

在您的情况下,您可以将图片附加到 self 变量,或者也许是画布。

In your case, you could attach the image to your self variable, or maybe the canvas. It doesn't really matter, as long as it is assigned to something.

self.image = photo
#or:
self.__canvas3.image = photo

这篇关于Python Tkinter 2.7问题与图像。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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