使用python tkinter显示图像时出现问题

时间:2017-08-01 15:59:00

标签: python-3.x tkinter

在一些早期的代码中,我已经能够创建一个单独的框架并使用tkinter在python中显示图像,但现在我试图编写一些首先要求参与者ID的代码(在第一帧中)然后显示ID和图像(在第二帧中)。不幸的是,图像不会显示在第二帧中: - (

以下代码正常工作,直到在第一帧按下Enter后调用启动功能。第二帧显示参与者ID,但不显示图像。在启动功能中,我试图简单地重复代码来创建第二帧,我之前用它来创建第一帧,尽管我似乎仍然无法显示gif图像。 / p>

from tkinter import *
from tkinter import ttk 

def start(*args):
    try:
        setPID = participantID
        startframe.destroy()
        imageframe = ttk.Frame(root, padding="30 15 10 10")
        imageframe.grid(column=0, row=0, sticky=(N, W, E, S))
        imageframe.columnconfigure(0, weight=1)
        imageframe.rowconfigure(0, weight=1)
        ttk.Label(imageframe, textvariable=setPID).grid(column=2, row=1, sticky=(W, E))
        ttk.Label(imageframe, text="participant ID").grid(column=1, row=1, sticky=W)
        for child in imageframe.winfo_children(): child.grid_configure(padx=5, pady=5)
        label = ttk.Label(root)
        image1 = PhotoImage(file='/home/mj8/Dropbox/pythonImage/dog.gif')
        label['image'] = image1
        label.grid(column=10, row=10)
    except ValueError:
        pass

#
# Set up main window 
#
root = Tk() 
root.title("Experiment")

#
# create a frame widget, which will hold all the content
# of our user interface, and place that in our main window
#
startframe = ttk.Frame(root, padding="30 15 10 10")
startframe.grid(column=0, row=0, sticky=(N, W, E, S))
#
# if the main window is resized, the frame should expand to
# take up the extra space
#
startframe.columnconfigure(0, weight=1)
startframe.rowconfigure(0, weight=1)

#
# Create main widgets were "action" happens, such as
# entering a value, and button pressing
participantID = StringVar()
setPID = StringVar()
participantID_entry = ttk.Entry(startframe, width=7,  textvariable=participantID) 
participantID_entry.grid(column=2, row=1, sticky=(W, E))
ttk.Button(startframe, text="Start", command=start).grid(column=2, row=2, sticky=W)

#
# Place the widget in the grid (placement of static text labels)
#
ttk.Label(startframe, text="participant ID").grid(column=1, row=1, sticky=W)

#
# Adding padding around all grid content (make it pretty)
#
for child in startframe.winfo_children(): child.grid_configure(padx=5, pady=5)

participantID_entry.focus() # starting placement of cursor
root.bind('<Return>', start) # if user presses 'return', run start

root.mainloop()

1 个答案:

答案 0 :(得分:1)

这是许多地方描述的常见问题,例如this page底部的大警告框。您需要保留对photoimage的引用。这通常通过将photoimage附加到Label实例来完成。在你的情况下:

label.image1 = PhotoImage(file='/home/mj8/Dropbox/pythonImage/dog.gif')
label['image'] = label.image1