Python Forum
tkinter showing image in button - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: GUI (https://python-forum.io/forum-10.html)
+--- Thread: tkinter showing image in button (/thread-33983.html)



tkinter showing image in button - rwahdan - Jun-16-2021

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()


RE: tkinter showing image in button - deanhystad - Jun-16-2021

Looks like there is a linefeed at the end of your filename.


RE: tkinter showing image in button - rwahdan - Jun-16-2021

(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.


RE: tkinter showing image in button - Yoriz - Jun-16-2021

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