0

I am trying to create a function for multiple buttons that allows the user to click on a specific button and change the associated image. For now I'm trying to change the image of a single button, but the image doesn't seem to be loaded or recognized for some reason. Any ideas?

import tkinter as tk
from tkinter import simpledialog,filedialog,colorchooser,messagebox,Frame,Button
from PIL import ImageTk, Image


def img_mod():
    global btn
    ret = filedialog.askopenfilename()
    loadn = Image.open(ret)
    root.render2 = ImageTk.PhotoImage(loadn)
    btn['image'] = loadn


root = tk.Tk()

load1 = Image.open("example.jpg")
root.render1 = ImageTk.PhotoImage(load1)

btn = tk.Button(root, text="My Button", image = root.render1)
btn['command'] = img_mod

btn.pack(fill='both', expand=True)
root.mainloop()

You can run this Python code if you save it with an image titled "example.jpg" in the same folder.

Wes Tomer
  • 319
  • 1
  • 13
  • What happens if you do `btn['image'] = root.render2`? – Bryan Oakley Jul 06 '20 at 21:53
  • @BryanOakley the reason I didn't do `btn['image'] = root.render2` is because I want this to be a function call that only happens when you press the button. So I assign the `'command'` as the function. – Wes Tomer Jul 07 '20 at 14:53
  • You can't supply a function to the `image` attribute. – Bryan Oakley Jul 07 '20 at 15:02
  • I solved my problem. I'm using lambda now: `R1C0= tk.Button(canv_1, image=root.render1, command = lambda: change_img(1))` This allows me to change the widget image. However it seems temporary since it disappear after I change another button image. (I'll post a separate question for this) – Wes Tomer Jul 08 '20 at 19:17

0 Answers0