AppJar从文件路径显示图像/图片

时间:2018-07-03 14:41:13

标签: python image tkinter filepath


我正在研究一个脚本,该脚本允许用户在其计算机上选择一个文件(图像),然后在脚本中对其进行处理。所有这些都没有问题。脚本的最后一部分使用AppJar创建GUI,并显示从先前处理中收集的信息。但是,唯一不起作用的是使用GUI显示用户在开始时选择的图像。以下是代码片段,这些代码片段负责上述功能。     

选择文件

Tk().withdraw() 
filename = askopenfilename() 
print(filename)
Tk().destroy()

启动GUI并添加图片:

app = gui()
app.setImageLocation(filename)
app.addImage(Processed_Image, filename, compound=None)
for i in range(0, extractor):
    app.addLabel(f"f{number}", labels1[diction_counter])
    number += 1
    diction_counter += 1
app.go()

除图像外,GUI均有效。返回以下错误:

Exception: Invalid image location: /Users/xxx/Pictures/2017_10_31/IMG_5271.JPG

我感谢有关如何解决此问题的所有提示。

+++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++

更新日期:
在尝试了XanderMJ和Malte提出的解决方案之后,唯一仍然无法按预期方式工作的是GUI中的图像。但是,文件的位置(一开始就是问题)已由Malte提出的代码解决。但是在运行代码时,我收到以下错误消息:

app.addImage("Analyzed", filename, compound=None)
File "/Users/XXX/anaconda3/lib/python3.6/site-packages/appJar/appjar.py", line 
7118, in addImage
self._addImageObj(name, imgObj, row, column, colspan, rowspan, 
compound=compound)
File "/Users/XXX/anaconda3/lib/python3.6/site-packages/appJar/appjar.py", line 
7144, in _addImageObj
label.config(anchor=CENTER, 
font=self._getContainerProperty('labelFont'),image=img)
File "/Users/XXX/anaconda3/lib/python3.6/tkinter/__init__.py", line 1482, in 
configure
return self._configure('configure', cnf, kw)
File "/Users/XXX/anaconda3/lib/python3.6/tkinter/__init__.py", line 1473, in 
_configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist

有关此错误的有趣部分是,开头选择的图像未称为pyimage1,但具有诸如“ img_1245.jpg”的名称。此外,将代码作为单独的程序运行,而没有将变量作为文件或路径的名称,则代码可以正常工作。以下是我刚才提到的有无变量的代码部分。

此代码不会引起问题:

from appJar import gui 
from PIL import Image, ImageTk

app = gui()
app.setImageLocation("/Users/XXX/Desktop")
app.addImage("test", "road.jpg")
app.zoomImage("test", -3)
app.go()

此代码会导致先前显示的错误:

app = gui()
app.setImageLocation(directory)
app.addImage("Analyzed", filename)
for i in range(0, extractor):
app.addLabel(f"f{number}", labels1[diction_counter])
number += 1
diction_counter += 1
app.go()

2 个答案:

答案 0 :(得分:1)

快速浏览一下AppJar文档:link

.setImageLocation(location)设置图像文件的文件夹。它将被放置在所使用的任何图像文件的名称之前。

目前,您正在尝试指定查找图像的路径,但是您提供的路径是1张图像的路径。将其更改为app.setImageLocation(folder_paht),然后在使用app.addImage('file.png')时为图像提供一个文件名。

因此,您必须获取文件的文件夹路径,我建议检查this post有关获取文件夹路径而不是文件路径。然后,您可以列出此文件夹中具有特定扩展名(link)的所有文件

希望这会有所帮助!

答案 1 :(得分:0)

通过将文件路径功能更新为以下内容,您可以单独提取目录,带有文件名的目录和文件名:

Tk().withdraw() 
path = askopenfilename() 
filename = os.path.basename(path)
directory = os.path.split(path)[0]
Tk().destroy()

如果尚未导入import os.path,则需要导入。
此外,要显示图像/图片,应执行以下操作:

app.setImageLocation(directory)
app.addImage(title, file, compound=None)

希望这会有所帮助!

相关问题