Reputation: 45
I'm trying to change an image button to an image label. Pressing the button should change the image of the button to label with an other image. And after that it should still be possible to press other image buttons.
I have code which I got from here: Python tkinter: Replacing an image button with an image label
from tkinter import *
class Game:
def __init__(self):
self.__window = Tk()
self.gifdir = "./"
self.igm = PhotoImage(file=self.gifdir+"empty.gif")
self.btn = Button(self.__window, image=self.igm, command = self.change_picture)
self.btn.grid(row=1, column=2, sticky=E)
self.btn2 = Button(self.__window, image=self.igm, command = self.change_picture)
self.btn2.grid(row=1, column=1, sticky=E)
self.__window.mainloop()
def change_picture(self):
self.igm = PhotoImage(file=self.gifdir+"new.gif")
self.btn.configure(image = self.igm)
def main():
Game()
main()
If I press the other button I'm not able to press the other one anymore and I would like to change pressed button to a label.
Upvotes: 2
Views: 1294
Reputation: 238081
I modified the code to use multiple references for buttons and images:
from tkinter import *
class Game:
def __init__(self):
self.__window = Tk()
self.gifdir = "./"
self.imgs = [PhotoImage(file=self.gifdir+"empty.gif"),
PhotoImage(file=self.gifdir+"empty.gif")]
self.btns = []
btn1 = Button(self.__window, image=self.imgs[0],
command = lambda: self.change_picture(0))
btn1.grid(row=1, column=2, sticky=E)
self.btns.append(btn1)
btn2 = Button(self.__window, image=self.imgs[1],
command = lambda: self.change_picture(1))
btn2.grid(row=1, column=1, sticky=E)
self.btns.append(btn2)
self.__window.mainloop()
def change_picture(self, btn_no):
self.imgs[btn_no] = PhotoImage(file=self.gifdir+"new.gif")
self.btns[btn_no].configure(image = self.imgs[btn_no])
def main():
Game()
main()
The references to buttons and images are stored in lists. change_picture was change to take button number as an argument, so that you can distinguish which button is pressed.
With these changes, each button can be pressed independently so that the image changes when pressed.
Upvotes: 3