how to put an image to each button in use (for loop) in python

126 views Asked by At

I want to create a loop to create several buttons, and put a different image in each button. but it shows that on the last button, -noted: when I run in (debug) step by step, it works. -it's been two days since I search on google thank you in advance

    from tkinter import *

    win = Tk()
    win.geometry("800x600")
    win.title("hhh")


    ls = ['/home/decode/Images/ImageDB/tom.png', '/home/decode/Images  /ImageDB/aub.png','/home/decode/Images/ImageDB/res.png']
    z=0
    #g= ls[z]


    for i in range(3):
        g= ls[z]
        img = PhotoImage(file=g)
        btn = Button(win, image=img)
        btn.pack()
        z+=1



    win.*mainloop*()

enter image description here`` enter image description here

1

There are 1 answers

1
رضا آلناصر On

You want to use the PIL library and PhotoImage, for example:

from tkinter import *
from PIL import* Image,Tkimage

win = Tk()
win.geometry("800x600")
win.title("hhh")

photo_1=PhotoImage(file=r'D:/button.png')

photo_image=Button(win,image=photo_1)
photo_image.place(x=10,y=0,height=12,width=12)

win.mainloop()