Tkinter dropdown Menu with keyboard shortcuts?

∥☆過路亽.° 提交于 2019-12-31 12:13:55

问题


I would like to have a Dropdown Menu in Tkinter, that includes the shortcut key associated with this command. Is this possible?

How would I also add the underline under a certain character, to allow for Alt-F-S (File->Save)?


回答1:


import tkinter as tk
import sys

class App(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        menubar = tk.Menu(self)
        fileMenu = tk.Menu(menubar, tearoff=False)
        menubar.add_cascade(label="File", underline=0, menu=fileMenu)
        fileMenu.add_command(label="Exit", underline=1,
                             command=quit, accelerator="Ctrl+Q")
        self.config(menu=menubar)

        self.bind_all("<Control-q>", self.quit)

    def quit(self, event):
        print("quitting...")
        sys.exit(0)

if __name__ == "__main__":
    app = App()
    app.mainloop()



回答2:


Maybe

from tkinter import *
import tkinter.filedialog as filed

root = Tk()
root.title("My Python Tkinter Application")
root.minsize(800,600)

def openfile():
    fn = filed.askopenfilename(filetypes=[("Text Files","*.txt")], title="Open File")
    f = open(fn, "r").read()
    print(f)

def init():
    menu = Menu(root)
    filemenu = Menu(menu)
    filemenu.add_command(label="Open (⌘O)", command=openfile)
    menu.add_cascade(label="File", menu=filemenu)
    root.config(menu=menu)
def key():
    print("Key Pressed: "+repr(event.char))
root.bind("<Key>", key)


来源:https://stackoverflow.com/questions/3485397/tkinter-dropdown-menu-with-keyboard-shortcuts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!