How to apply font defined in JSON file to tkinter ttk Button using a custom theme?

Question:

I am trying to create a custom theme for my tkinter application using a JSON file. I have defined the properties for a ttk Button in the JSON file, including the font family and size. However, when I apply the theme to my Button, the font is not applied (though the background is).

Here’s a simplified version of my code:

from tkinter import Tk
from tkinter.ttk import Button, Style
from json import load

root = Tk()
style = Style()

# test.json
"""
{
    "TButton": {
        "configure": {
            "background": "red",
            "font": {
                "family": "Helvetica",
                "size": 20
            }
        }
    }
}
"""

style.theme_create("MyStyle", parent="clam", settings=load(open("test.json")))
style.theme_use("MyStyle")

btn = Button(root, text="Example")
btn.pack()

root.mainloop()

As you can see, I’m using the load() method from the JSON module to load the properties for the TButton widget. However, the font is not being applied to the Button.

I’ve read the documentation on how to use fonts with tkinter here and found this SO question, but it assumes that a font has been created with the Font object, and that it is named. I don’t want to have to create a font object in Python and then use that name in the JSON file (though, even after doing that, it still doesn’t work).

How can I define the font in the JSON file and apply it to my ttk Button using a custom theme? I believe there is probably a way to accomplish this with buitlin methods but the documentation on this is very sparse and I have not found anything on this issue.

Asked By: TRCK

||

Answers:

Edit: Add style.theme_create

However, when I apply the theme to my Button, the font is not applied
(though the background is).

In line 22, comment it out as I am not familiar json.

Correct way to use style.theme_create.

Snippet:

from tkinter import Tk
from tkinter.ttk import Button, Style
from json import load

root = Tk()
style = Style()

# test.json
style.theme_create("MyStyle", parent="clam", settings={    
    "TButton": {
        "configure": {
            "background": "red",
            "font": {
                "family": "Helvetica",
                "size": 20
            }
        }
    }
}
) 

#style.theme_create("MyStyle", parent="clam", settings=load(open("test.json")))
style.theme_use("MyStyle")

btn = Button(root, text="Example")
btn.pack()

root.mainloop()

Screenshot:

enter image description here

Answered By: toyota Supra

The font option expects either an instance of font.Font() or a string like "Helvetica 20" or a tuple/list like ["Helvetica", 20], so change "font" inside the JSON to:

"font": "Helvetica 20"

or

"font": ["Helvetica", 20]
Answered By: acw1668
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.