使用 Tkinter 制作文件选择器 GUI 以显示输入和输出文件
Posted
技术标签:
【中文标题】使用 Tkinter 制作文件选择器 GUI 以显示输入和输出文件【英文标题】:Using Tkinter to make a file chooser GUI to display both input and output file 【发布时间】:2018-12-17 15:26:50 【问题描述】:我正在使用 python 3、opencv 和 tkinter 创建一个 GUI,我可以在其中上传图像,然后将图像显示在最终图像旁边的面板中,该图像是与输入的图像。 stacker() 函数只是将文件夹中的图像堆叠起来。
由于某种原因,在运行该程序时,应该在 panelA 中的图像正在显示,而 panelB 中的图像却没有。
如何同时显示图像 - 输入和输出? 还有什么办法可以加快这段代码的速度吗?
def select_image():
# grab a reference to the image panels
global panelA, panelB
# open a file chooser dialog and allow the user to select an input
# image
path = tkinter.filedialog.askopenfilename()
# ensure a file path was selected
if len(path) > 0:
# load the image from disk, convert it to grayscale, and detect
# edges in it
image = cv2.imread(path)
edged = stacker(os.path.dirname(os.path.dirname(path)))
# OpenCV represents images in BGR order; however PIL represents
# images in RGB order, so we need to swap the channels
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# convert the images to PIL format...
image = Image.fromarray(image)
edged = Image.fromarray(edged)
# ...and then to ImageTk format
image = ImageTk.PhotoImage(image)
edged = ImageTk.PhotoImage(edged)
# if the panels are None, initialize them
if panelA is None or panelB is None:
# the first panel will store our original image
panelA = tk.Label(image=image)
panelA.image = image
panelA.pack(side="left", padx=10, pady=10)
# while the second panel will store the edge map
panelB = tk.Label(image=edged)
panelB.image = edged
panelB.pack(side="right", padx=10, pady=10)
# otherwise, update the image panels
else:
# update the pannels
panelA.configure(image=image)
panelB.configure(image=edged)
panelA.image = image
panelB.image = edged
# initialize the window toolkit along with the two image panels
root = tk.Tk()
panelA = None
panelB = None
print("done")
# create a button, then when pressed, will trigger a file chooser
# dialog and allow the user to select an input image; then add the
# button the GUI
btn = tk.Button(root, text="Select an image", command=select_image)
print("done1")
btn.pack(side="bottom", fill="both", expand="yes", padx="10", pady="10")
print("done2")
# kick off the GUI
root.mainloop()
print("done3")
【问题讨论】:
你的代码在我看来没问题。显然我无法测试它,因为您没有提供minimal reproducible example 和一些测试图像。因此,我猜问题出在您的 stacker() 函数中;也许它返回一个空数组? 您的意思是两次使用os.path.dirname
吗?这会将您放在父文件夹中,而不是“与输入图像相同的文件夹”。
@Novel 感谢您发现这个错误,我已修复它。我现在不允许提供 stacker() 函数,但是如果我尝试在不同的面板中显示两次输入图像,程序甚至无法工作。
如果两个标签都使用“图像”,您的代码对我有效。向我们展示一个 minimal reproducible example 来证明您的问题。
图像是否显示两次?在左面板和右面板? @小说
【参考方案1】:
您的代码按预期工作,但由于图像的大小,这两个图像可能都没有显示。我建议调整图像的大小。
edged = cv2.resize(edged, dsize=(500, 600), interpolation=cv2.INTER_CUBIC)
【讨论】:
此外,您可能需要检查图像类型或 numpy 与 python 数组的兼容性。【参考方案2】:可能无法显示两张图像的原因是图像的大小。我建议使用调整大小功能来确保无论输入图像大小如何都能显示图像。
我已经提供了一个代码 sn-p,它应该如下所示。
edged = cv2.resize(edged, dsize=(500, 600), interpolation=cv2.INTER_CUBIC)
【讨论】:
以上是关于使用 Tkinter 制作文件选择器 GUI 以显示输入和输出文件的主要内容,如果未能解决你的问题,请参考以下文章
Python Chapter 9: 使用Tkinter进行GUI程序设计 Part 2