how to make tkinter <Enter> event work when <button-1> is pressed?

蹲街弑〆低调 提交于 2019-12-31 03:05:14

问题


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.

来源:https://stackoverflow.com/questions/47944322/how-to-make-tkinter-enter-event-work-when-button-1-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!