How to create a transparent rectangle reacting to a click event in Tkinter

I need to draw a rectangle in tkinter.canvas to respond to a click event:

click_area = self.canvas.create_rectangle(0,0,pa_width,pa_height,fill='LightBlue',outline='lightBlue',tags=['A','CLICK_AREA'])


it works.

at this point, I have to draw a series of grids on the canvas, and I want them to be covered with click_area

, so I need to render them transparent click_area


but when I wrote like this:

click_area = self.canvas.create_rectangle(0,0,pa_width,pa_height,fill='',outline='lightBlue',tags=['A','CLICK_AREA'])


he pressed not to press more.

So my question is how to make it transparent and make it responsive when clicked. Or, is there any other way to implement what I want.

Many thanks.


source to share

3 answers

I think I got it: Anchor the canvas, not the rectangle.







problem solved.



I ran into this same problem while trying to use the find_closest

Canvas method to modify existing rectangles, but simply snapping to the canvas didn't work. The problem is that a Tkinter rectangle with no fill will only respond to clicks on its border.

Then I read about the argument argument create_rectangle

from here :

tipple: Bitmap showing how the inside of the rectangle will be outlined.

The default is "=" "which means a solid color. A typical value would be value =" gray25 ". Has no effect if padding was set to some color. See Section 5.7," Bitmaps " .

The bitmaps section states that only a few options are available by default, but none of them are completely transparent. However, you can specify your own bitmap as an X bitmap (file .xbm


XBM files are just text files with type C syntax, so I made my own 2x2 bitmap with all transparent pixels and saved it as transparent.xbm

in the same directory as my Tkinter script. Here's the code for the XBM file:

#define trans_width 2
#define trans_height 2
static unsigned char trans_bits[] = {
   0x00, 0x00


Then you can specify a custom template prefixing the filename xbm

with @

when you create your rectangle:

    fill='gray',  # still needed or stipple won't work


Note that you still need to provide some sort of padding value, or the overlay will not be applied. The actual value of the fill is irrelevant, as cropping will "override" it on the canvas.



I need to do the same and I am using an xbm file, but I still get a gray filled rectangle.



All Articles