使用路径数组显示图像对

2024-10-04 05:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想加载一组图像,将它们分成两组,然后在窗口中并排显示这些图像。我还要添加一个按钮来选择要显示的对

    def select_files():
        files = filedialog.askopenfilenames(title="Select photo", filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*")))   
        # many lines of code for the algorithm that splits images into pair
        pairs.append([photo1, photo2])      


    root = Tk()

    selectButton = Button(root, text="Select", command=select_files)
    selectButton.place(x=5, y=500)


    show_first = ImageTk.PhotoImage(img1)
    show_second = ImageTk.PhotoImage(img2)

    panel1 = Label(root, image=show_first)
    panel1.place(x=5, y=5)

    panel2 = Label(root, image=show_second)
    panel2.place(x=200, y=5)


    root.geometry("%dx%d+500+500" % (550, 550))
    root.mainloop()

但如何传递图像以先显示\然后再显示\呢

pairs.append([photo1, photo2])photo1photo2行中的p.S.都是路径存储在photo1[0]中,图像大小存储在photo1[1]中的列表


Tags: 图像showplacerootfilesselectfirstappend
1条回答
网友
1楼 · 发布于 2024-10-04 05:34:13

问题是tkinter回调¹不直接支持参数和²忽略返回值。这个问题是可以解决的¹使用带有默认参数和²使用可变对象(例如列表)作为默认参数,因为当回调函数修改它时,更改会反映在调用者作用域中

例如,你可以用一个参数来定义select_files,一个列表,这是一个你可以随意修改的可变参数

def select_files(pairs):
    pairs.clear()  # this voids the content of the list
    # many lines of code for the algorithm that splits images into pairs
    pairs.append(['a.jpg', 'b.jpg'])

然后,在main中修改command=...以引入默认参数

pairs = []
...
selectButton = Button(root, text = "Select",
                      command = lambda pairs=pairs: select_files(pairs))

因此,最终,您可以访问每对图像文件名

for fn1, fn2 in pairs:
    ...

在实践中证明

>>> def gp(pairs):
...     pairs.append([1,2])
... 
>>> pairs = []
>>> (lambda p=pairs: gp(p))() 
>>> pairs
[[1, 2]]
>>> 

还有一个反例

>>> def gp(pairs):
...     pairs = [[1, 2]]
... 
>>> pairs = []
>>> (lambda p=pairs: gp(p))() 
>>> pairs
[]
>>> 

这表明您应该从不赋值给函数参数

相关问题 更多 >