Search code examples
python-3.xtkinterttk

Is there a way to assign various images based upon a ttk button state?


I'm working with a GUI and I would like to set my ttk buttons up with various images depending on the state of the button. For example:

import tkinter as tk
from tkinter import PhotoImage, ttk

activeImage = PhotoImage(file="images/active.png")
disabledImage = PhotoImage(file="images/disabled.png")
normalImage = PhotoImage(file="images/normal.png")

button = ttk.Button(frame,\
                    activeimage=activeImage,\
                    disabledimage=disabledImage, \
                    normalimage=normalImage,\
                    command=lambda pass)

I'm not finding anything in the tk docs that explains how to do this, nor on this site. My apologies if this has already been asked somewhere else.


Solution

  • Yes, the ttk widgets support mapping attributes to states with the map method of a Style.

    For example:

    style = ttk.Style()
    style.map(
        "Custom.TButton",
        image=[
            ("disabled", disabledImage),
            ("!disabled", normalImage),
            ("active", activeImage)
        ]
    )
    

    Next, create a button with this style:

    button = ttk.Button(frame, style="Custom.TButton")
    

    The tkdocs.com site has a nice tutorial on creating custom styles. See Styles and Themes