In Tkinter's Menu, you can make it look nice by specifying the accelerator option when adding a menu button with a command, but in reality this alone does not enable keyboard shortcuts. Work to associate with the method is required. Here is a sample for that.
import tkinter as tk
from tkinter import ttk
class Application(tk.Frame):
def __init__(self,master):
super().__init__(master)
self.pack()
self.master.geometry("300x300")
self.master.title("Menubar Sample")
self.create_menubar()
def create_menubar(self):
menubar = tk.Menu(self)
file_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Open", command=self.onOpen, accelerator="Ctrl+O")
self.master.config(menu=menubar)
self.bind_all("<Control-o>", self.onOpen)
def onOpen(self, event=None):
print("onOpen")
def main():
root = tk.Tk()
app = Application(master=root)
app.mainloop()
if __name__ == "__main__":
main()
OnOpen is linked to the application with self.bind_all. When executing onOpen with a keyboard shortcut, event is passed as an argument, but it is not passed when the menu button is clicked directly. Therefore, the initial value of event is set to None to correspond to the latter. If this is a hassle, let's define it separately.
Recommended Posts