将新图像放置在新的网格位置

Placing a new image in a new grid position

我遇到了这样的情况,我想按下按钮并添加一张图片。我已经设法完美地获得了第一张图片,但是当我按下按钮添加下一张图片时,它只是将它堆叠在最上面。有什么方法可以让我每次按下按钮时移动新条目的位置以停止堆叠??

images = []
def add_friend():
    x = 0
    x += 1
    global friendImage
    friendFrame.filename = filedialog.askopenfilename(initialdir= "/coursework - current/images/", title= "Select a friend",)
    friendImage = ImageTk.PhotoImage(Image.open(friendFrame.filename).resize((100,150), Image.NEAREST))
    friendImageInsert = Label(friendFrame, image=friendImage)
    friendImageInsert.grid(row= 0, column=x, sticky="NW")
    friendImageLabel = Label(friendFrame, text=friendFrame.filename.split("/")[-1])
    friendImageLabel.grid(row= 1, column=x)
    images.append(friendImageInsert)
    images.append(friendImageLabel)

所以这是现在的样子:

如果我要打开一个新图像并将其放入。我怎样才能让它以相同的格式将下一个图像放在它旁边的列中?我希望它为我添加的每一个都将它放在一个新列中

首先你需要使x成为一个全局变量并在函数外初始化它。其次,你不应该对所有添加的图像使用相同的全局变量 friendImage,因为它会使之前添加的图像被垃圾收集。使用标签的属性来存储图像。您也可以将文件名和图像放在一个标签中,而不是两个标签中。

labels = []
x = 0
def add_friend():
    global x
    filename = filedialog.askopenfilename(initialdir="/coursework - current/images/", title="Select a friend")
    image = ImageTk.PhotoImage(Image.open(filename).resize((100,150), Image.NEAREST))
    filename = os.path.basename(filename)
    friendImageLabel = Label(friendFrame, compound="top", image=image, text=filename, bd=1, relief='raised')
    friendImageLabel.grid(row=0, column=x, sticky="nsew")
    friendImageLabel.image = image # save a reference of image to avoid garbage collected
    labels.append(friendImageLabel)
    x += 1