python - 如何使用键盘快捷键/绑定(bind)激活 tkinter 菜单和工具栏?

标签 python python-3.x tkinter tkinter-menu

我在 tkinter 中有一个文件菜单,当我单击它时,会打开一个文件菜单。我还希望菜单使用诸如“alt+f”之类的键盘快捷键打开,而不是单击它。
这是代码:

def Open_FileMenu_With_KeyboardShortcut():
    pass
    # How would I make the file menu appear when I click "Alt+f"
root.bind("<the code for alt-f>", Open_FileMenu_With_KeyboardShortcut)

# File Option for Menu Bar 
FileOption = Menu(MenuBar, tearoff=False)
MenuBar.add_cascade(label="File", menu=FileOption, underline=0)
FileOption.config(bg="White", fg="Black", activebackground="Whitesmoke", activeforeground="Black", activeborderwidth=1, font=('Monaco', 11))
# New Option for File Option
NewMenu = Menu(FileOption, tearoff=False)
NewMenu.config(bg="White", fg="Black", activebackground="Whitesmoke", activeforeground="Black", activeborderwidth=1, font=('Monaco', 11))
NewMenu.add_command(label="New File", command=NewFile)
NewMenu.add_command(label="From Template", command=None)
# Cascade the New menu to the File Menu
FileOption.add_cascade(label="New", menu=NewMenu)
# The remaining settings options
FileOption.add_command(label="Open File", command=OpenFile, accelerator="Ctrl+O")
FileOption.add_command(label="Open Folder", command=None, accelerator="Ctrl+Shift+O")  
FileOption.add_command(label="Open Recent", command=None)
FileOption.add_separator()
FileOption.add_command(label="Save File", command=SaveFile, accelerator="Ctrl+S")
FileOption.add_command(label="Save As", command=SaveFileAs, accelerator="Ctrl+Shift+S")
FileOption.add_separator()
FileOption.add_command(label="Revert File", commmand=None)
FileOption.add_command(label="Close Editor", command=None, accelerator="Ctrl+W")
FileOption.add_separator()
FileOption.add_command(label="Quit", command=QuitApplication, accelerator="Ctrl+q")
如何使用键盘快捷键打开文件菜单?

最佳答案

我不是 100% 确定问题在问什么,但根据我对问题的理解,这应该有效:

import tkinter as tk

root = tk.Tk()

MenuBar = tk.Menu(root, tearoff=False) # Create the main menu
root.config(menu=MenuBar) # Assign it to the root

# File Option for Menu Bar 
FileOption = tk.Menu(MenuBar, tearoff=False)
MenuBar.add_cascade(label="File", menu=FileOption, underline=0)
...
FileOption.add_command(label="Quit", command=exit, accelerator="Ctrl+q")
Altf同时会打开文件菜单。

关于python - 如何使用键盘快捷键/绑定(bind)激活 tkinter 菜单和工具栏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66162880/

相关文章:

Python Rest客户端api上传文件

python - 无法从C++中的.dat文件提取实际数据?

python - Tkinter 网格布局不会扩展

Python3 - 字符串的最后一个字符

python - 我如何从列表(每个索引独立) - 在字典中 - 写入条目列表?

Python 在函数调用中添加增量变量

python - Tkinter:从一帧获取变量以在另一帧中显示为标签

python - 我可以在 for 循环中启动计数器(以跳过一些迭代次数)吗?

python - 最常见的字符 - 用户提交的没有字典或计数器的字符串

python - 将元素附加到Python数组的列表之一