Search code examples
pythonbuttontkinterttk

I am facing issue with tkinter button style "_tkinter.TclError: Invalid state name a"


I was trying to do a exercise on making a onscreen keyboard using tkinter and I almost completed the program and it works fine but the issue is when I was doing some last minute touch-ups like setting a style for key I encountered an error.

style=ttk.Style()
style.configure("mybutton.TButton", font=("montserrat", "10", "bold"), 
                foreground="white", background="green")
style.configure("myBigbutton.TButton", font=("monserrat", "24", "bold"), 
                foreground="white", background="green")
style.map("myButton.TButton", background=('active', 'green'))

I'm defining two different styles for two different kinds of buttons and when I use this map condition I'm getting an error _tkinter.TclError: Invalid state name a. If I change active to pressed I will get _tkinter.TclError: Invalid state name p as error.


Solution

  • Based on the documentation of the Style.map() method,

    Each key in kw is an option and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, lists, or some other preference.

    Which simply means you need to nest the value of the statespecs — each of which is sequence — for the background keyword inside an outer list or tuple even when there is only one.

    In other words, you need to write the value as shown below:

    style.map("myButton.TButton", background=[('active', 'green')])