Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用Tkinter显示图像_Python_Tkinter - Fatal编程技术网

Python 用Tkinter显示图像

Python 用Tkinter显示图像,python,tkinter,Python,Tkinter,我正在开发一个python程序,该程序使用Tkinter和ImageTk显示一系列图像。我只能显示一张图像。下面是一个复制错误的完整小程序。程序直接递归地搜索当前的jpg文件,并在用户按Enter键时显示它们 import Tkinter, ImageTk,os, re def ls_rec(direc): try: ls = os.listdir(direc) except Exception as e: return for f i

我正在开发一个python程序,该程序使用Tkinter和ImageTk显示一系列图像。我只能显示一张图像。下面是一个复制错误的完整小程序。程序直接递归地搜索当前的jpg文件,并在用户按Enter键时显示它们

import Tkinter, ImageTk,os, re


def ls_rec(direc):
    try:
        ls = os.listdir(direc)
    except Exception as e:
        return
    for f in os.listdir(direc):
        fpath = os.path.join(direc, f)
        if os.path.isfile(fpath):
            yield fpath
        elif os.path.isdir(fpath):
            for f2 in iterate_dir(os.path.join(direc,f)):
                yield f2

images = filter(lambda a:re.match('.*\\.jpg$',a),ls_rec(os.getcwd()))
assert(len(images)>10)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
Label_text = Tkinter.Label(top,text="Below is an image")
img = None
i = 0



def get_next_image(event = None):
    global i, img
    i+=1
    img = ImageTk.PhotoImage(images[i])
    label.config(image=img)
    label.image = img

top.bind('<Enter>',get_next_image)
label.pack(side='bottom')
Label_text.pack(side='top')
get_next_image()
top.mainloop()
导入Tkinter、ImageTk、os、re
def ls_rec(目录):
尝试:
ls=os.listdir(direc)
例外情况除外,如e:
返回
对于os.listdir(direc)中的f:
fpath=os.path.join(direc,f)
如果os.path.isfile(fpath):
收益率路径
elif os.path.isdir(fpath):
对于迭代_dir(os.path.join(direc,f))中的f2:
产量f2
images=filter(lambda:re.match('.\\\.jpg$',a),ls_rec(os.getcwd())
断言(len(图像)>10)
top=Tkinter.Tk()
图像标签=Tkinter.label(顶部)
Label\u text=Tkinter.Label(顶部,text=“下面是图像”)
img=无
i=0
def get_next_图像(事件=无):
全球i,img
i+=1
img=ImageTk.PhotoImage(图像[i])
label.config(image=img)
label.image=img
顶部绑定(“”,获取下一张图片)
标签。包装(侧边和底部)
标签_text.pack(side='top')
获取下一张图片()
top.mainloop()
程序因以下回溯而失败:

Traceback (most recent call last):
  File "/usr/lib/python2.7/pdb.py", line 1314, in main
    pdb._runscript(mainpyfile)
  File "/usr/lib/python2.7/pdb.py", line 1233, in _runscript
    self.run(statement)
  File "/usr/lib/python2.7/bdb.py", line 387, in run
    exec cmd in globals, locals
  File "<string>", line 1, in <module>
  File "/home/myuser/Projects/sample_images.py", line 1, in <module>
    import Tkinter, ImageTk,os, re
  File "/home/myuser/Projects/sample_images.py", line 32, in get_next_image
    img = ImageTk.PhotoImage(some_image[1])
  File "/usr/lib/python2.7/dist-packages/PIL/ImageTk.py", line 109, in __init__
    mode = Image.getmodebase(mode)
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 245, in getmodebase
    return ImageMode.getmode(mode).basemode
  File "/usr/lib/python2.7/dist-packages/PIL/ImageMode.py", line 50, in getmode
    return _modes[mode]
KeyError: '/home/myuser/sampleimage.jpg'
回溯(最近一次呼叫最后一次):
文件“/usr/lib/python2.7/pdb.py”,第1314行,在main中
pdb.\u运行脚本(mainpyfile)
文件“/usr/lib/python2.7/pdb.py”,第1233行,在运行脚本中
self.run(语句)
文件“/usr/lib/python2.7/bdb.py”,第387行,正在运行
全局、局部中的exec cmd
文件“”,第1行,在
文件“/home/myuser/Projects/sample_images.py”,第1行,在
导入Tkinter、ImageTk、os、re
文件“/home/myuser/Projects/sample\u images.py”,第32行,在get\u next\u image中
img=ImageTk.PhotoImage(一些图片[1])
文件“/usr/lib/python2.7/dist packages/PIL/ImageTk.py”,第109行,在__
mode=Image.getmodebase(模式)
getmodebase中的文件“/usr/lib/python2.7/dist packages/PIL/Image.py”,第245行
返回ImageMode.getmode(mode).basemode
文件“/usr/lib/python2.7/dist packages/PIL/ImageMode.py”,第50行,在getmode中
返回模式[模式]
KeyError:“/home/myuser/sampleimage.jpg”
运行此代码时,是否有人获得相同的行为?我做错了什么

编辑:使用korylprince的解决方案,并进行一些清理,以下是原始代码的工作版本:

import os, re, Tkinter, ImageTk

def ls_rec(direc, filter_fun=lambda a:True):
    for (dirname, dirnames, fnames) in os.walk(direc):
        for fname in fnames:
            if filter_fun(fname):
                yield os.path.join(dirname,fname)


top = Tkinter.Tk()
image_label = Tkinter.Label(top)
text_label = Tkinter.Label(top,text="Below is an image")
images = ls_rec(os.getcwd(), lambda a:re.match('.*\\.jpg$',a))

imgL = []

def get_next_image(event = None):
    fname = images.next()
    print fname
    fhandle = open(fname)
    img = ImageTk.PhotoImage(file=fhandle)
    fhandle.close()
    imgL.append(img)
    image_label.config(image=img)


top.bind('<Return>',get_next_image)
image_label.pack(side='bottom')
text_label.pack(side='top')
get_next_image()
top.mainloop()
导入操作系统、re、Tkinter、ImageTk
def ls_rec(direc,filter_fun=lambda a:True):
对于os.walk(direc)中的(dirname、dirnames、fnames):
对于fnames中的fname:
如果过滤器(fname):
生成os.path.join(dirname,fname)
top=Tkinter.Tk()
图像标签=Tkinter.label(顶部)
text\u label=Tkinter.label(顶部,text=“下面是图像”)
images=ls_rec(os.getcwd(),lambda:re.match('.\\\.jpg$',a))
imgL=[]
def get_next_图像(事件=无):
fname=images.next()
打印fname
fhandle=打开(fname)
img=ImageTk.PhotoImage(文件=fhandle)
fhandle.close()
imgL.append(img)
image\u label.config(image=img)
顶部绑定(“”,获取下一张图片)
图像\u标签。包装(侧面='bottom')
text_label.pack(side='top')
获取下一张图片()
top.mainloop()

编辑:
top.bind(“”…
实际绑定鼠标进入帧的事件,而不是用户按Enter键。正确的行是
top.bind(“”,…)
ImageTk.PhotoImage
没有正确的文档记录

您应该尝试以下方法:

#outside of functions
images = list()

#inside function
global images
with open(images[i]) as f:
    img = ImageTk.PhotoImage(file=f)
    images.append(img)

将图像放在列表中的原因是为了让python有一个对它的引用。否则,垃圾收集器将最终删除图像对象。

ImageTk。PhotoImage
没有正确记录

您应该尝试以下方法:

#outside of functions
images = list()

#inside function
global images
with open(images[i]) as f:
    img = ImageTk.PhotoImage(file=f)
    images.append(img)

将图像放在列表中的原因是为了让python有一个对它的引用。否则,垃圾收集器最终将删除映像对象。

您不使用映像对象有什么原因吗?没有。我只是知道os.walk。我在我的个人库中实现了这个ls_rec,所以它不会打扰我。但是是的,glob更简单。实际上,glob不是递归的。所以这毕竟是有原因的。你不使用有原因吗?没有。我只是知道os.walk。我在我的个人库中实现了这个ls_rec,所以它不会打扰我。但是是的,glob更简单。实际上,glob不是递归的。所以这毕竟是有原因的,我同意。多亏了这个模块,我浪费了很多时间。我尝试了你的解决方案,确实消除了最初的错误。我现在遇到了另一个我也经常看到的错误:TclError:image“pyimage10”不存在我搜索了这个错误。一些人声称这与照片图像在没有足够的引用时被垃圾收集有关。但我似乎已经解决了这个可能的问题。现在怎么办?知道为什么“图像”pyimage10“不存在”吗?另外,你知道在img被实例化后是否可以关闭该文件吗?我刚刚更新了我的答案。基本上,您必须在图像对象中保持某些引用处于打开状态,否则它将被删除。由于您一直在重新绑定img,图像将被删除。您的解决方案成功了!我试着把图片放在列表中,放在一个全局变量中,等等。似乎我同时犯了两个错误,而且我从未同时纠正过这两个错误。谢谢最后一件事:您知道我什么时候可以关闭文件吗?使用
with
语句在上下文管理器中打开文件。基本上,这意味着在with语句块完成后,文件被关闭(这就是上下文管理器对文件所做的)。我猜
PhotoImage
会将文件加载到内存中。我同意。多亏了这个模块,我浪费了很多时间。我尝试了你的解决方案,确实消除了最初的错误。我现在遇到了另一个我也经常看到的错误:TclError:image“pyimage10”不存在,我已经搜索过了