我正在尝试使用Tkinter在Python 2.7中显示图像。下面是我尝试使用的代码示例,它显示了文件夹中的所有图像(来自 http://code.activestate.com/recipes/521918-pil-and-tkinter-to-display-images/):
import os, sys
import Tkinter
import Image, ImageTk
def button_click_exit_mainloop (event):
event.widget.quit() # this will cause mainloop to unblock.
root = Tkinter.Tk()
root.bind("<Button>", button_click_exit_mainloop)
root.geometry('+%d+%d' % (100,100))
dirlist = os.listdir('.')
old_label_image = None
for f in dirlist:
try:
image1 = Image.open(f)
root.geometry('%dx%d' % (image1.size[0],image1.size[1]))
tkpi = ImageTk.PhotoImage(image1)
label_image = Tkinter.Label(root, image=tkpi)
label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1])
root.title(f)
if old_label_image is not None:
old_label_image.destroy()
old_label_image = label_image
root.mainloop() # wait until user clicks the window
except Exception, e:
# This is used to skip anything not an image.
# Image.open will generate an exception if it cannot open a file.
# Warning, this will hide other errors as well.
pass
例如,十字(顶部)将在Tkinter窗口(底部)中显示以下显示的图像:
我尝试了其他代码(包括一些显示我的网络摄像头),它们都导致相同的结果:我可以看到一个图像,它有正确的尺寸,但每列都有一个恒定的像素值(一个原始图像的第一行的相应列)。