Title: Make an option menu that displays images in Python and tkinter
The program uses the following code to create its OptionMenu.
# Make an OptionMenu.
# Make a dictionary mapping text values to images.
self.light_images = {
'red' : tk.PhotoImage(file='red_light.png'),
'yellow' : tk.PhotoImage(file='yellow_light.png'),
'green' : tk.PhotoImage(file='green_light.png'),
}
# Make the OptionMenu.
self.light_var = tk.StringVar(value='red')
self.light_om = tk.OptionMenu(self.window,
self.light_var, 'red', 'yellow', 'green',
command=self.light_selected)
self.light_om.configure(image=self.light_images['red'])
# Get the underlying menu.
menu = self.light_om['menu']
# Add the menu item images.
for text, image in self.light_images.items():
menu.entryconfigure(text, image=image, compound=tk.NONE)
self.light_om.pack(side=tk.TOP, padx=10, pady=10)
The code first creates a dictionary mapping names (red, yellow, and green) to their corresponding images. It then makes a StringVar, initially setting its value to red.
Next, the code creates the OptionMenu, giving it the same key values (red, yellow, and green) and setting its initial value to red. It then configures the new widget so it displays the red image.
The code then needs to make the menu's options display their images. The OptionMenu doesn't allow direct access to its menu items, but it's basically a fancy wrapper for a more normal menu that does allow that access. To set the option images, the first code gets the OptionMenu's underlying menu.
It then loops through the image dictionary's values and configures the options so they display their corresponding images. To do that, it uses each dictionary key to configure the option that has that key as its text (red, yellow, or green). It configures the option so it displays the image stored for that key in the dictionary.
Notice that the code sets each option's compound property to tk.NONE. That property determines where the image should be drawn with respect to the position of the text for options that have both. The value tk.NONE tells the option to display only its image.
After it finishes configuring the menu, the program packs it.
That's the end of the code that creates and configures the menu. The last piece to the puzzle, which is shown in the following code, makes the OptionMenu display a new image when the user selects one.
def light_selected(self, light_name):
# Give the OptionMenu the correct image.
print(f'Light: {light_name}')
self.light_om.configure(image=self.light_images[light_name])
When the user selects an option, the program executes the light_selected method. This method's second parameter holds the value that was selected. In this example, that's one of the strings red, yellow, or green. The method prints out that value so you can see it. It then uses the image dictionary to look up the corresponding image and configures the OptionMenu to display it.
Download the example to see additional details.
|