As I’ve stated before, I’ve always loved the command line. It’s where I’ve been most comfortable. I cut my chops writing C and assembly, and really started my career writing Mumps/Cache code all from the command line.
Recently I’ve been challenging myself to get into writing for the GUI. I have a few Udemy courses lined up for android development, and promised myself I’d write a gui for at least one of my Python experiments.
While researching Python GUIs, I’ve settled on tkinter as my weapon of choice. The documentation, as far as I’ve seen, is scattered and release dependent. So cobbling the minimum together I’ve come up with the following framework to get at minimum a window with a menu attached.
Feel free to use the code to start your journey!
# different versions have diff tkinters # let's do right by this try: import tkinter except ImportError: import Tkinter as tkinter # placeholder for this example def hello(): pass # from the docs # The Tk class is instantiated without arguments. # This creates a toplevel widget of Tk which usually # is the main window of an application. # Each instance has its own associated Tcl interpreter. mainWindow = tkinter.Tk() # Here are our main window params, including # the window title, how big is the window # and some padding, because mainWindow.title("Main Window Title") mainWindow.geometry('640x480-8-200') mainWindow['padx'] = 10 # our main menubar is attached to the window created above # we don't give this a name or anything, it's the base menu # we'll use to attach our real menus main_menu = tkinter.Menu(mainWindow) # Here's the good stuff. We create a menu from tkinter.menu class # and attach it to the main_menu menubar. we add our commands # to each menu item as a cascade. We can do this for each # individual menu main_util_menu = tkinter.Menu(main_menu, tearoff=0) main_util_menu.add_command(label="Do Some Stuff", command=hello) main_util_menu.add_command(label="Doing Other Stuff", command=hello) main_file_menu = tkinter.Menu(main_menu, tearoff=0) main_file_menu.add_command(label="Save", command=hello) main_file_menu.add_command(label="Open", command=hello) main_file_menu.add_separator() main_file_menu.add_command(label="Exit", command=main_menu.quit) # Now we just need to add each menu, in order main_menu.add_cascade(label="File", menu=main_file_menu) main_menu.add_cascade(label="Database", menu=main_util_menu) # set up the main window to use our menubar mainWindow.config(menu=main_menu) # redraw and start the fun! mainWindow.update() mainWindow.mainloop()