Tkinter 将鼠标点击绑定到框架 [英] Tkinter bind mouse clicks to frame

查看:38
本文介绍了Tkinter 将鼠标点击绑定到框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定遗漏了一些明显的东西,我的 Tkinter 程序中有两个框架,每个框架在网格布局中都有一堆标签.我想将鼠标点击绑定到其中一个而不是另一个.我目前使用

I must be missing something obvious, I have two frames in my Tkinter program, each with a bunch of labels in a grid layout. I want to bind the mouseclick to one of them but not the other. I currently use

root.bind("<Button-1>", mouse_function)

但是如果我在另一个框架中单击也会触发.我假设使用

but that also triggers if I click in the other frame. I assumed that using

schedule_frame.bind("<Button-1>", mouse_function)

会起作用,但后来我在任何地方都没有得到回应.

would work but then I get no response anywhere.

我调用的函数是:

def mouse_function(event):
    y = event.widget.grid_info()['row']
    x = event.widget.grid_info()['column'] 
    widgets[(y, x)].configure(state="active")
    shiftSelection(y,x)

推荐答案

当您绑定到根窗口时,该绑定将应用于该根窗口中的所有小部件.这就是它为任一帧触发的原因.这是 tkinter 的标准行为.

When you bind to the root window, that binding applies to all widgets in that root window. That is why it triggered for either frame. This is standard behavior for tkinter.

当您将绑定移动到框架时,它停止工作,因为框架从未看到该事件.当你点击标签时,看到绑定的是标签,而不是框架(除非你点击标签之间的空间)

When you move the binding to the frame, it stopped working because the frame never saw the event. When you click on the label, it is the label that sees the binding, not the frame (unless you click in the space between labels)

至少有三种方法可以解决这个问题.一是您可以将装订放在标签上而不是框架上.另一种方法是将绑定保留在根窗口上,但在函数内检查小部件是否是该框架的子窗口.

There are at least three ways to solve this problem. One is that you can put the binding on the labels rather than the frame. Another is to keep the binding on the root window, but within the function check to see if the widget is a child of that one frame.

第三种解决方案涉及更改标签的绑定标签.有关深入示例,请参阅此答案:https://stackoverflow.com/a/32771893/7432

A third solution involves changing the bind tags for the labels. For an in depth example see this answer: https://stackoverflow.com/a/32771893/7432

这篇关于Tkinter 将鼠标点击绑定到框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆