Tkinter Menubutton 小部件键绑定以在同一窗口中打开菜单小部件元素 [英] Tkinter Menubutton widget key binding to open Menu widget elements in same window
问题描述
我使用 Menubutton
和 Menu
小部件在菜单内创建了一个子菜单:
I have created a submenu inside a menu using Menubutton
and Menu
widgets:
from tkinter import *
root = Tk()
def f(event):
submenu.invoke(0)
mainmenu = Menubutton(root, text="Menu")
mainmenu.pack()
submenu = Menu(mainmenu)
mainmenu.config(menu=submenu)
submenu.add_command(label="Option 1")
submenu.add_command(label="Option 2")
现在我想给我的菜单添加一个键绑定:
Now I want to add a key binding to my menu:
mainmenu.bind("<Key>", f)
mainmenu.focus_set()
它很有魅力:当我按下一个键时,它会打开子菜单.但问题是,子菜单是作为一个被撕掉的顶层窗口打开的.但我希望它与菜单在同一个窗口中打开.我将 tearoff=0
添加到 submenu
(所以它变成了这样:submenu = Menu(mainmenu, tearoff=0)
).但是现在,它不返回任何东西.我试图弄清楚为什么它没有.也许我做错了什么...
我一直在寻找解决方案,但没有一个能解决问题.他们所说的只是添加一个打印出一些东西的键绑定,但是我想要一个键绑定有点自动点击菜单项,它弹出项目元素,但不是作为一个单独的窗口(也许它被称为 上下文菜单
?).我在任何地方都找不到针对此特定问题的任何解决方案.
那么我怎样才能让它发生呢?任何帮助将不胜感激.
It works as charm: when I press a key, it opens up the submenu. But the problem is, the submenu is opened as a torn off toplevel window. But I want it to be opened in same window with menu. I added tearoff=0
into submenu
(so it became like this:submenu = Menu(mainmenu, tearoff=0)
). But now, it does not return anything. I'm trying to figure out why it doesn't. Maybe I'm doing something wrong...
I have looked for a solution, but none of them solves the problem. All they tell is just adding a key binding that prints out something, however I want a key binding that kinda automatically clicks on a menu item, and it pops up the item elements, but not as a separate window (maybe it's called contextmenu
?). I couldn't find any solution to this specific problem anywhere.
So how can I make it happen? Any help would be appreciated.
推荐答案
我认为
def f(event):
submenu.post(mainmenu.winfo_rootx(),
mainmenu.winfo_rooty() + mainmenu.winfo_height())
做你想做的事,即使有 tearoff=False
选项.
does what you want, even with the tearoff=False
option.
这篇关于Tkinter Menubutton 小部件键绑定以在同一窗口中打开菜单小部件元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!