Reputation: 1123
I added a png image with transparent regions (alpha=0) to a tkinter canvas (see minimal example below). A mouse-click is recognized when clicking somewhere in the rectangle that contains the tkinter image.
How do I adjust the functionality such that any mouse binding (clicking, moving, etc.) is only called when the mouse is located on pixels with non-zero alpha values of the image?
Tux (linux mascot) example image :
try:
# Tkinter for Python 2.xx
import Tkinter as tk
except ImportError:
# Tkinter for Python 3.xx
import tkinter as tk
image_path = "./tux.png"
class Application(tk.Frame):
def __init__(self, master):
self.master = master
tk.Frame.__init__(self, master)
self.canvas = tk.Canvas(self, width=600, height=600)
self.canvas.pack(fill="both", expand=True)
# create an example image
self.tk_image = tk.PhotoImage(file=image_path)
self.image_obj= self.canvas.create_image(200, 200, anchor = 'center',
image=self.tk_image)
self.canvas.tag_bind(self.image_obj, '<Button-1>', self.clicked)
def clicked(self, event):
print("I am tux.")
def main():
app_win = tk.Tk()
app = Application(app_win).pack(fill='both', expand=True)
app_win.mainloop()
if __name__ == '__main__':
main()
Upvotes: 0
Views: 65
Reputation: 386210
How do I adjust the functionality such that any mouse binding (clicking, moving, etc.) is only called when the mouse is located on pixels with non-zero alpha values of the image?
You can't. That's simply not something that tkinter directly supports. Unfortunately, tkinter's support of transparency is a bit lacking.
What you might be able to do, however, is have the bound function get the image object, compute which pixel was clicked on, and then query the image instance to get the color of that pixel.
Upvotes: 2