How to change the image of a button in tkinter

76 views Asked by At

I'm trying to program buttons for a game in tkinter, which change the picture randomly. However, on the one hand I don't know how to randomize the buttons so that a random button changes its layout, and then how the button changes its layout. I've tried different things and my last attempt was .config(). I hope you can help me! Thank you Max

from tkinter import *
import random
# Create Object
root = Tk()

score = 0

#first image
photo1 = PhotoImage(file = r"C:/Users/m_buchner/Pictures/180px-U+25CF.svg.png")

#buttons
img0 = Button(root, image = photo1,
            borderwidth = 0)
img0.grid(row=1, column=1)
img1 = Button(root, image = photo1,
            borderwidth = 0)
img1.grid(row=1, column=2)
img2 = Button(root, image = photo1,
            borderwidth = 0)
img2.grid(row=1, column=3)
img3 = Button(root, image = photo1,
            borderwidth = 0)
img3.grid(row=2, column=1)
img4 = Button(root, image = photo1,
            borderwidth = 0)
img4.grid(row=2, column=2)
img5 = Button(root, image = photo1,
            borderwidth = 0)
img5.grid(row=2, column=3)

label = Label(root, width=20, height=2, text=score)
label.grid(row=0, column=2)

label = Label(root, width=20, height=2, text=score)
label.grid(row=0, column=2)




root.mainloop()

def change_button():
    
    photo1 = PhotoImage(file = r"C:/Users/m_buchner/Pictures/180px-U+25CF.svg.png")
    photo2 = PhotoImage(file = r"C:/Users/m_buchner/Pictures/Screenshot 2022-05-02 195231.png")
    
    img0.configure(root, image = photo2,
                borderwidth = 0)

    img1.configure(root, image = photo1,
                borderwidth = 0)

    img2.configure(root, image = photo1,
                borderwidth = 0)

    img3.configure(root, image = photo1,
                borderwidth = 0)

    img4.configure(root, image = photo1,
                borderwidth = 0)

    img5.configure(root, image = photo1,
                borderwidth = 0)

Thank you very much for your help! ❤

0

There are 0 answers