<p>问题是您过早地释放了<code>PhotoImage</code>对象。在</p>
<p>如<a href="http://effbot.org/tkinterbook/photoimage.htm" rel="nofollow">the docs</a>解释:</p>
<blockquote>
<p>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.</p>
<p>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.</p>
<p>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:</p>
</blockquote>
<pre><code>label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
</code></pre>
<p>您可能认为将其作为<code>image</code>参数传递给<code>Label</code>构造函数可以使其保持活动状态。但是它没有;<code>Label</code>实际上并没有保留对<code>PhotoImage</code>对象的引用,只有在<code>mainloop</code>开始之后运行的Tcl代码中的实际标签构造才这样做。(这类似于弱引用,但不是有意的或明确的引用,如果有帮助的话)</p>
<p>因此,快速而棘手的解决方案是要么将其添加到<code>extractedMethod</code>的顶部:</p>
^{pr2}$
<p>…或在<code>label1 = Label(image=photo1)</code>行后添加:</p>
<pre><code>label1.photo = photo1
</code></pre>
<hr/>
<p>避免这种情况的一个更好的方法是使用OO设计而不是平面过程设计,这样您就有了一些合理的对象来拥有所有的引用。在</p>
<p>即使是琐碎的版本,如<a href="http://www.ittc.ku.edu/~niehaus/classes/448-s04/448-standard/simple_gui_examples/" rel="nofollow">these examples</a>所示也可以:</p>
<pre><code>class Foo(object):
def __init__(self, root):
# put the code from extractedMethod here,
# but prefix every local variable with self,
# and do the same for myCallback.
def myCallback(self):
pass
</code></pre>
<p>但是你最好使用一个真正的OO设计,你的对象实际上代表一些东西,比如<a href="http://docs.python.org/2/library/tkinter.html#a-simple-hello-world-program" rel="nofollow">the official examples</a>:</p>
<pre><code>class MyFrame(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.create_widgets()
def myCallback(self):
pass
def create_widgets(self):
# put the code from extractedMethod here,
# again prefixing things with self
</code></pre>