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

Tkinter Menu组件中使用activate()方法时如何避免菜单自动关闭?

解决Tkinter菜单点击命令后无法保留菜单并激活选项的问题

要实现点击菜单命令后不关闭菜单并激活指定选项,核心思路是在菜单默认关闭后重新弹出菜单,再调用activate()方法。以下是修改后的代码和关键说明:

修改后的代码

import tkinter as tk

def on_open():
    print("Stop1")
    # 获取菜单弹出的坐标(基于根窗口位置偏移,可按需调整)
    x = root.winfo_rootx() + 10
    y = root.winfo_rooty() + 30
    # 延迟执行重新弹出操作,避开菜单默认关闭的逻辑
    root.after(10, lambda: file_menu.post(x, y))
    # 激活索引为1的「Save」选项
    file_menu.activate(1)
    print("Stop2")

root = tk.Tk()
root.geometry("400x200")

menu_bar = tk.Menu(root)
root.config(menu=menu_bar)

file_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="File", menu=file_menu)

file_menu.add_command(label="Open", command=on_open)
file_menu.add_command(label="Save", command=lambda: print("Save selected"))
file_menu.add_command(label="Exit", command=root.quit)

root.mainloop()

关键说明

  • 延迟弹出菜单:使用root.after(10, ...)是因为点击菜单命令后,Tkinter会优先执行菜单关闭的默认逻辑,延迟执行能让重新弹出的操作在关闭之后生效。
  • 菜单定位:file_menu.post(x, y)需要指定弹出坐标,这里用根窗口的偏移坐标保证菜单位置和原位置一致,也可根据实际需求调整。
  • 激活选项:重新弹出菜单后调用activate(1),就能直接看到指定选项被高亮的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:42:52