You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter获取触发事件的Widget问题:事件绑定重复响应

Tkinter事件冒泡问题:鼠标悬停Frame时父组件也触发事件

最小可复现示例

from tkinter import *

def test(event):
    print(event.widget)

window = Tk()
window.geometry("600x600")
window.bind("<Motion>", test)

frame = Frame(window, bg="red", width=200, height=200)
frame.pack()
frame.bind("<Motion>", test)

window.mainloop()

问题描述

鼠标移过不同Widget时希望各自调用test函数,但鼠标悬停在Frame上时,Window和Frame的回调都会执行,且都输出触发事件的是Frame,不符合预期。

问题原因

Tkinter的事件默认存在冒泡传递机制:子组件触发事件后,事件会向上传递给其父组件,导致父组件的绑定回调也被触发。

解决方法

在子组件的回调函数中返回"break",即可阻止事件继续向上冒泡传递,父组件的回调就不会被触发。

修改后的代码:

from tkinter import *

def test(event):
    print(event.widget)
    # 阻止事件向上冒泡
    return "break"

window = Tk()
window.geometry("600x600")
window.bind("<Motion>", test)

frame = Frame(window, bg="red", width=200, height=200)
frame.pack()
frame.bind("<Motion>", test)

window.mainloop()

内容的提问来源于stack exchange,提问作者Bananenkris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 09:20:41