Home > Mobile >  Placing a new image in a new grid position
Placing a new image in a new grid position

Time:03-12

I have situation here where I want to press the button and add an image in. I have managed to get the first in perfectly but when I press the button to add the next one in it just stacks it on top. is there a way that I can move the position of a new entry every time I press the button to stop it stacking??

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)

so here is what it looks like right now:

If I was to open a new image and to place it in. How could I get it to place the next image in the column next to it in the same format? I want it to place it in a new column for every one that I add

CodePudding user response:

First you need to make x a global variable and initialize it outside the function. Second you should not use same global variable friendImage for all images added because it will make the previously added image to be garbage collected. Use an attribute of the label to store the image instead. Also you can put the filename and the image together in a label instead of two labels.

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
  • Related