So ive been tinkering with Tkinter and Pillow for a project of mine and have so far come up with a clickable image. When i click the image it prints image has been clicked. However i want the image to get destroyed before the text is displayed. I have tried img.destroy() but that throws and error saying img is not defined so i suspect the problem is that i dont understand where things have been renamed and such. any and all help is greatly appreciated :)
from tkinter import *
from PIL import Image, ImageTk
SWH = Tk()
SWH.geometry("1024x950+130+0")
SWH.title("ServiceWhiz.")
def printimage():
load = Image.open("hello.gif")
render = ImageTk.PhotoImage(load)
img = Button(SWH, image=render,command=imgpress)
img.image = render
img.place(x=0,y=0)
return;
def imgpress():
img.destroy()
Label1 = Label(SWH, text="Image has been clicked",fg="#0094FF",font=('Arial',20)).pack()
return;
SWTitle = Label(SWH, text="ServiceWhiz.",fg="#0094FF",font=('Arial',20)).pack()
MyButtonTest = Button(SWH, text="Click Me.",fg="White",bg="#0094FF",command=printimage).pack()
You need to define "img" variable outside of your printimage function (on the same layer as for SWH). If you defined img inside of the function it will be accessible only there. By adding global img we specify that img inside of function should refer to that global-level value. It's a generally bad idea to have it like this so think about moving your handlers into class which will retain state and store img for you.
Try to make like this:
from tkinter import *
from PIL import Image, ImageTk
SWH = Tk()
SWH.geometry("1024x950+130+0")
SWH.title("ServiceWhiz.")
img = None
def printimage():
global img
load = Image.open("hello.gif")
render = ImageTk.PhotoImage(load)
img = Button(SWH, image=render,command=imgpress)
img.image = render
img.place(x=0,y=0)
return;
def imgpress():
global img
img.destroy()
Label1 = Label(SWH, text="Image has been clicked",fg="#0094FF",font=('Arial',20)).pack()
return;
SWTitle = Label(SWH, text="ServiceWhiz.",fg="#0094FF",font=('Arial',20)).pack()
MyButtonTest = Button(SWH, text="Click Me.",fg="White",bg="#0094FF",command=printimage).pack()