Taylor's Blog

Atypical ramblings

Working with OptionMenus

One of the cool things about the Tkinter module is how quickly you can go from a concept sketch:

20150420_102048 (Medium)

to a skeleton framework that approximates your program:

Frame

One of the major problems I have had with my program is figuring out how to get one OptionMenu widget (the drop down menus in the middle) to automatically alter the contents of another OptionMenu based on what is selected. The most common response you will see appears to be this one. While functional, I find that solution very convoluted and hard to follow (at least for someone just starting out like myself), so I set out on a quest to find an easier way (although at the time of writing this I have just stumbled upon this simpler answer).

My new solution involves using some code found in the ttk module. The following are the steps I took to get ttk running with Python 3.

  1. Setup your computer’s command prompt to allow access to the “python” command. To do this, go to your computer properties page and click on advanced system settings. Click environment variables down at the bottom. In the system variables box, find “path” and click “edit.” At the end of the variable value line, add a semi colon (;) and then type in the directory that points to your Python installation. For me, it was C:\Python34. Now, whenever you are in your computer’s command prompt, you can type “Python” and do all sorts of Python commands. Neat!
  2. Next you need to download and extract the ttk files. You can find them here.
  3. Now you need to install ttk. Open your command prompt and navigate to where the ttk setup.py file is and type the following: python setup.py install
  4. You can confirm that ttk has been installed by going into your Python shell and typing “help()” and then “modules” without the quotes.

(For a more detailed look, you can watch this handy tutorial video.)

Hooray! Now ttk is installed and we can the awesome method known as set_menu. This does exactly what you think it does: it allows you to set the menu as something new! It’s so simple! No complicated variables, lambdas, or for statements! Here’s a look at a very simple program I made that alters the contents of an OptionMenu when a button is pressed:
[python]
from tkinter import *
from ttk import *

root = Tk()

def buttFunction():
myMenu.set_menu(‘New item 1’, ‘New item 2′)

a = StringVar(root)
a.set(“select”)

myMenu = OptionMenu(root, a, “Item 1”, “Item 2”)
myMenu.pack()

butt = Button(root, text=’push’, command=buttFunction)
butt.pack()

root.mainloop()
[/python]Oh… dang. I just realized that by importing everything from ttk, I have caused the .set() method in tkinter to stop working. There must be a way to just import the set_menu() method and nothing else. Back to the books I guess…

Updated: April 23, 2015 — 5:25 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

Taylor's Blog © 2015