python clickable image

Solutions on MaxInterview for python clickable image by the best coders in the world

showing results for - "python clickable image"
Yannick
28 Jun 2018
1import tkinter as tk
2from PIL import Image, ImageTk
3
4# --- functions ---
5
6def on_click(event=None):
7    # `command=` calls function without argument
8    # `bind` calls function with one argument
9    print("image clicked")
10
11# --- main ---
12
13# init    
14root = tk.Tk()
15
16# load image
17image = Image.open("image.png")
18photo = ImageTk.PhotoImage(image)
19
20# label with image
21l = tk.Label(root, image=photo)
22l.pack()
23
24# bind click event to image
25l.bind('<Button-1>', on_click)
26
27# button with image binded to the same function 
28b = tk.Button(root, image=photo, command=on_click)
29b.pack()
30
31# button with text closing window
32b = tk.Button(root, text="Close", command=root.destroy)
33b.pack()
34
35# "start the engine"
36root.mainloop()
37