pythontkintertkinter-button

Using Tkinter colorchooser erases button image and disables button


I am making a simple Python GUI to allow the user to choose a color using Tkinter colorchooser. The user will click a button to open the colorchooser, and I'd like that button to have an image instead of text. However, after you use the colorchooser, the image is deleted from the button and the button is disabled. Any ideas what is causing this failure?

If I use text for the button instead of an image, there is no problem using colorchooser.

import tkinter as tk
from tkinter import colorchooser

class MainGUI(tk.Tk):
    def __init__(self):
        super().__init__()
        addImage = r'C:\Documents\Scripting\VisualStudio\ClispiPy\ClispiPy\Images\Add.png'
        addPhoto = tk.PhotoImage(file = addImage)
        tk.Button(self, image=addPhoto, command=self.open_sub_gui).pack(pady=20)

    def open_sub_gui(self):
        col = colorchooser.askcolor(title='Select Color')
        return

if __name__ == "__main__":
    main_gui = MainGUI()
    main_gui.mainloop()

Before using colorchooser:

Before UI Image

After using colorchooser:

After Image


Solution

  • The key fix is simply adding self. to store the PhotoImage as an instance variable instead of a local variable.

    The full code is provided below:

    import tkinter as tk
    from tkinter import colorchooser
    
    class MainGUI(tk.Tk):
        def __init__(self):
            super().__init__()
            addImage = r'add.png'
            self.addPhoto = tk.PhotoImage(file=addImage)  # Store as instance variable
            tk.Button(self, image=self.addPhoto, command=self.open_sub_gui).pack(pady=20)
    
        def open_sub_gui(self):
            col = colorchooser.askcolor(title='Select Color')
            return
    
    if __name__ == "__main__":
        main_gui = MainGUI()
        main_gui.mainloop()
    

    Output:

    I used my own plus sign image.

    enter image description here