0

蟒蛇版本:2.7

我正在尝试创建一个使用 tkinter 简单地加载 2 个图像的函数。我的代码是:

from Tkinter import *

class ImageTest(object):
    def __init__(self):

        self.window = Tk()
        self.window.geometry('300x300')

        testImg = PhotoImage(file='test.gif')
        label1 = Label(self.gameWindow, image=testImg )
        label1.pack()
        label2 = Label(self.gameWindow, image=testImg )
        label2.pack()

        #self.init_test_screen()

        self.window.mainloop()

    def init_test_screen(self):

        testImg = PhotoImage(file='test.gif')
        label1 = Label(self.gameWindow, image=testImg )
        label1.pack()
        label2 = Label(self.gameWindow, image=testImg )
        label2.pack()

imagetest = ImageTest()

这按预期工作,但我想要做的是将 label1 和 label2 的初始化委托给 init_test_screen()。如果我将我的初始化更改为:

def __init__(self):

        self.window = Tk()
        self.window.geometry('300x300')

        #testImg = PhotoImage(file='test.gif')
        #label1 = Label(self.gameWindow, image=testImg )
        #label1.pack()
        #label2 = Label(self.gameWindow, image=testImg )
        #label2.pack()

        self.init_test_screen()

        self.window.mainloop()

不再显示 2 张图像。关于为什么的任何想法?

4

1 回答 1

2

The reference to "testImg" is lost after the execution of "init_test_screen". Just store it within the object using "self":

from Tkinter import *

class ImageTest(object):
    def __init__(self):

        self.window = Tk()
        self.window.geometry('300x300')

        self.init_test_screen()

        self.window.mainloop()

    def init_test_screen(self):

        self.testImg = PhotoImage(file='test.gif')
        label1 = Label(self.window, image=self.testImg )
        label1.pack()
        label2 = Label(self.window, image=self.testImg )
        label2.pack()

imagetest = ImageTest()
于 2013-09-28T12:32:04.863 回答