0

I am attempting to make a simple Tkinter app that displays an image on screen, and that reduces the brightness of the image when you click:

from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk, ImageEnhance

def update_image(img):
    enhancer = ImageEnhance.Brightness(img)
    temp_img = enhancer.enhance(0.5)
    temp_tkimg = ImageTk.PhotoImage(temp_img)
    panel.configure(image=temp_tkimg)

root = Tk()

img   = Image.open('img.png')
tkimg = ImageTk.PhotoImage(img)

panel = ttk.Label(root, image=tkimg)

panel.pack(side="bottom", fill="both", expand="yes")

panel.bind('<1>', lambda e: update_image(img))

root.mainloop()

This correctly displays the initial image, but after clicking, instead of rendering the new image it just disappears. I've tried saving the temp_tkimg as a new png and reopening it the same way I do with the initial image but this doesn't work either:

def update_image(img):
    enhancer = ImageEnhance.Brightness(img)
    temp_img = enhancer.enhance(0.5)
    temp_img.save('temp.png')
    temp_tkimg = PhotoImage(file='temp.png')
    panel.configure(image=temp_tkimg)

I feel like this is a pretty simple concept so not sure what I'm missing.

Cheers.

kbz.dev
  • 1
  • 1
  • Add `panel.tk_img = temp_tkimg` at the end of the function – TheLizzard Jul 15 '21 at 15:56
  • @TheLizzard that `panel.tk_img = temp_tkimg` did it thanks, I'm having a read through of the answer you linked now. – kbz.dev Jul 15 '21 at 16:00
  • I think I understand, that because `temp_tkimg` is instantiated inside the function it gets binned once the function ends. I'm still not 100% sure why `panel.configure(...)` doesn't work on it's own though. – kbz.dev Jul 15 '21 at 16:04
  • Call it a bug. `panel.configure` doesn't keep a reference to the image so yes the image gets binned after the function ends. – TheLizzard Jul 15 '21 at 16:15
  • there is bug in PhotoImage - see `Note` at the end of page [PhotoImage](https://web.archive.org/web/20201112023229/http://effbot.org/tkinterbook/photoimage.htm) – furas Jul 15 '21 at 18:04

0 Answers0