【问题标题】:How to activate tkinter menu and toolbar with keyboard shortcut/binding?如何使用键盘快捷键/绑定激活 tkinter 菜单和工具栏?
【发布时间】:2021-02-11 21:08:30
【问题描述】:

我在 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")

如何使用键盘快捷键打开文件菜单?

【问题讨论】:

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


【解决方案1】:

我不是 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会打开文件菜单。

【讨论】:

    【解决方案2】:

    将命令绑定到 root 时,您需要的只是 以及您要使用的密钥,在您的情况下是 f。

    root.bind("&lt;Alt-key-f&gt;", Open_FileMenu_With_KeyboardShortcut)

    【讨论】:

    • 好的,谢谢,但是当我点击 Alt-F 时如何打开文件菜单?
    • 我不知道如何打开文件菜单,但你这样做的功能将是第二个参数@Skcoder
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2018-02-24
    • 2014-03-25
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多