Python Forum

Full Version: tkinter showing image in button
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am trying to show an image in a button. the approch is to read the path from a file and that path is in the last line. I am able to read the path from the file but i can't add it to the button. It gives error it can't find the path.

  # find the last line for the photo
    with open(username1, 'rb') as f:
        f.seek(-2, os.SEEK_END)
        while f.read(1) != b'\n':
            f.seek(-2, os.SEEK_CUR)
        last_line = f.readline().decode()

    photo = PhotoImage(file=last_line)
    photoimage = photo.subsample(1, 2)

    Label(session_start, text="Welcome  " + username1).pack()
    Label(session_start, text="").pack()
    Label(session_start, text="").pack()
    Button(session_start, image=photoimage).pack(pady="150")
Note:
There was a new line break "\n" that I needed to take out. now I can see the space of the photo in the form but no image and yes i did pack()
Looks like there is a linefeed at the end of your filename.
(Jun-16-2021, 01:49 AM)deanhystad Wrote: [ -> ]Looks like there is a linefeed at the end of your filename.

I am new to programming with GUI. Do you mean extra line? I removed it and now no errors, just empty image box.
Try altering to the following code to keep a reference to the image otherwise the image can get garbage collected.
btn = Button(session_start, image=photoimage)
btn.pack(pady="150")
btn.photoimage = photoimage