Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

python - How do you change the state of multiple tkinter buttons when your mouse is pressed and hovering over it?

I have a 2d array of tkinter buttons.

It looks like this: enter image description here

I want to be able to click on a button, hold my mouse down, and every button that is hovered over while my mouse is pressed down changes colors. So far I have it to the point where if you hover over any square regardless if a mouse button is pressed it changes colors.

The code looks like this so far:

def draw(self, i, j):
    button = self.buttons[i][j] 
    button.bind('<Enter>', lambda event: self.on_enter(event, button))


def on_enter(self, e, button):
    button['background'] = 'green'

To be clear, I want to be able to change a button's color when left-click is held down and a button is hovered over at the same time.

Thanks for helping me.

EDIT: removed picture of code and provided something that can be copy and pasted.

2ND EDIT: the code is about 100 lines, but the gist is there's a 2d array of tkinter buttons, and the code I provided shows the 2 functions responsible for changing the color of the buttons. If more code is needed, I'll put it in.

question from:https://stackoverflow.com/questions/65933562/how-do-you-change-the-state-of-multiple-tkinter-buttons-when-your-mouse-is-press

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can bind <B1-Motion> on root window to a callback. Then inside the callback, use .winfo_pointerxy() to get the mouse position and .winfo_containing() to find which button is under the mouse pointer and change its background color:

Example:

def on_drag(event):
    x, y = root.winfo_pointerxy()
    btn = root.winfo_containing(x, y)
    if btn:
        btn.config(bg="green")

# root is the root window
root.bind('<B1-Motion>', on_drag)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...