zSynonym
zSynonym

Reputation: 31

Clickable Images for Python

I'm an entry level python coder looking to create a Guess Who styled game. At university, I've yet to learn how to import images and bind them to fixed places on a screen (resembling the game board). Is there any way to click on a specific image and have an onClickEvent to occur, where that specific character(image) is chosen. The majority of my coding abilities are in python, but I am skeptical if this is the best possible language to do a project like this in.

Upvotes: 2

Views: 23698

Answers (2)

furas
furas

Reputation: 142641

Every GUI has Button widget which is clickable and (mostly) can display image.

But mostly in GUI you can assign click event to every object ie. Label with Image.

ie. Tkinter

import tkinter as tk
from PIL import Image, ImageTk

# --- functions ---

def on_click(event=None):
    # `command=` calls function without argument
    # `bind` calls function with one argument
    print("image clicked")

# --- main ---
    
# init    
root = tk.Tk()

# load image
image = Image.open("image.png")
photo = ImageTk.PhotoImage(image)

# label with image
l = tk.Label(root, image=photo)
l.pack()

# bind click event to image
l.bind('<Button-1>', on_click)

# button with image binded to the same function 
b = tk.Button(root, image=photo, command=on_click)
b.pack()

# button with text closing window
b = tk.Button(root, text="Close", command=root.destroy)
b.pack()
    
# "start the engine"
root.mainloop()

Graphic modules like PyGame can display image too, and have click event but sometimes you have to check manually if you clicked in area with image (and you have to create mainloop manually)

Upvotes: 14

turnip
turnip

Reputation: 2346

I'd say TkInter is your best bet. A little bit cumbersome at first but it's good for beginners. You should be able to make a nice Graphical User Interface with it which will open a window that holds your pictures, menus, buttons, etc...

Take a look at useful docs and examples here.

If Python is not a requirement, I too would also recommend JS, HTML and CSS (you'll have to use all three together. Sounds scarier than it is :P)

Upvotes: 1

Related Questions