I want to fill rectangles just like in paint. When mouse button is pressed I want every rectangle I enter to be filled and otherwise I want no event to take place.
Here Is my code:
from tkinter import Canvas
import tkinter
_width = 50
_height = 50
_size = 8
root = tkinter.Tk()
root.title("draw me a lovely matrix")
canv = Canvas(root, width=_width * _size, height=_height * _size)
class Wrapper:
btn1d = False
def set_btn1d(value):
print(value)
Wrapper.btn1d = value
def toggle_color(rect):
print('called')
if Wrapper.btn1d:
color = canv.itemcget(rect, 'fill')
canv.itemconfig(rect, fill=("#aaa" if color == '#fff' else '#fff'))
rects = []
canv.bind('<ButtonPress-1>', lambda e, value=True: set_btn1d(value))
canv.bind('<ButtonRelease-1>', lambda e, value=False: set_btn1d(value))
for i in range(_size):
for j in range(_size):
rect = canv.create_rectangle(_width * j, _height * i, _width * (j + 1), _height * (i + 1), fill="#fff", width=0)
rects.append(rect)
canv.tag_bind(rect, '<Enter>', lambda e, rect=rect: toggle_color(rect))
canv.pack()
root.mainloop()
The problem is that when I press the mouse button only the cell in which the mouse was pressed detects the entrance of mouse pointer(also the one in which mouse will be released at the end)
Any beneficial general advice about my code would be of course much appreciated.
<Enter>
at all times when left click is pressed. – Naefind_closest
as a workaround. – Nae<B1-Enter>
similar to<B1-Motion>
but it doesn't seem to exist. – Nae