The behavior of OptionMenu in Tkinter is weird

25 views Asked by At

I want to add icons to the options in the dropdown menu. I implemented this using OptionMenu in Tkinter. The problem is that these icons are not displayed properly.

This is part of my code:

class DropDownMenu(tk.OptionMenu):
    def __init__(self, parent):

        self.curr_value = tk.StringVar()

        options_image, save_image, remove_image, replace_image = self.load_icons()
        actions_and_images = {"Зберегти копію": save_image, "Видалити": remove_image, "Замінити": replace_image}

        super().__init__(parent, self.curr_value, "", *list(actions_and_images.keys()))
        #self.config(image=options_image)

        for option, image in actions_and_images.items():
            self['menu'].entryconfigure(option, image=image, compound="left")


    def load_icons(self):
        options_icon = Image.open("./icons/options_icon.png").resize((25, 25))
        options_image = ImageTk.PhotoImage(options_icon, )

        save_icon = Image.open("./icons/save_icon.png").resize((25, 25))
        save_image = ImageTk.PhotoImage(save_icon)

        remove_icon = Image.open("./icons/remove_icon.png").resize((25, 25))
        remove_image = ImageTk.PhotoImage(remove_icon)

        replace_icon = Image.open("./icons/replace icon.png").resize((25, 25))
        replace_image = ImageTk.PhotoImage(replace_icon)

        return options_image, save_image, remove_image, replace_image

But when running the program, the icons are not displayed.

enter image description here

However, if you run the program in debug mode with a breakpoint on the line where the icons are added to the options, surprisingly it works.

enter image description here

enter image description here

The question is why this happens and how can I fix the code so that I don't have to do this hack every time.

0

There are 0 answers