简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM