gpt4 book ai didi

python - 如何使用 tkinter.filedialog Askopenfile 打开多张图片

转载 作者:行者123 更新时间:2023-12-01 04:29:29 25 4
gpt4 key购买 nike

我正在开展一个分析图像的大学研究项目,细节对于这个问题来说并不重要,为了清楚起见,我将省略这些部分。

我的代码非常适合单个图像,但我处理多个图像时遇到问题。 Tkinter 对此并没有很好的文档,我一直在努力弄清楚。

这是工作代码的示例

import matplotlib.pyplot as plt
from skimage import data
from tkinter.filedialog import askopenfile

image_formats= [("JPEG", "*.jpg")]
file_path = askopenfile(filetypes=image_formats, initialdir="/", title='Please select a picture to analyze')

image = data.imread(file_path.name)

plt.imshow(image)
plt.show()

此代码允许我单击一张图像以在 tkinter 菜单中打开,但不允许按住 Ctrl 键单击多个图像

如果我将每个“askopenfile”更改为“askopenfiles”,它允许我按住 Ctrl 键单击多个图像,但会引发错误:

image = data.imread(file_path.name)
AttributeError: 'NoneType' object has no attribute 'name'

我知道我必须循环打开每个图像,但我真的不知道我做错了什么,也不知道对多个图像执行此操作的正确方法是什么。

我正在寻找一个修复程序,允许用户按住 Ctrl 键单击多个图像,以便 tkinter 能够抓取文件路径并将它们放入列表中,以便 skimage 和 matplotlib 打开(并稍后进行分析)。

抱歉,如果这太复杂了,如果您需要更多解释或屏幕截图,我将非常乐意进行编辑,以便问题清楚。

最佳答案

如果您只想要名称,则应该使用 - askopenfilenames() 。示例-

import matplotlib.pyplot as plt
from skimage import data
from tkinter.filedialog import askopenfilenames

image_formats= [("JPEG", "*.jpg")]
file_path_list = askopenfilenames(filetypes=image_formats, initialdir="/", title='Please select a picture to analyze')

for file_path in file_path_list:
image = data.imread(file_path)

plt.imshow(image)
plt.show()

askopenfile() 实际上为您打开文件并返回该文件(或者 askopenfiles() 打开所有文件并返回它们)。我不太确定是什么导致 file_path 变成 None 。

关于python - 如何使用 tkinter.filedialog Askopenfile 打开多张图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32575969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com