tkinter and CustomTkinter · lesson 7 of 8
Parts in this lesson
Apip install customtkinter2.9: into the venv
Bctk.CTk()the main window
Cclass DeskWindow(ctk.CTkFrame)a new parent class
Dset_appearance_mode("system")light and dark

A modern look with CustomTkinter

Last updated

tkinter works everywhere, but its widgets look like they did years ago. CustomTkinter is a set of modern-looking widgets built on top of tkinter: rounded, flat, with light and dark modes. In this lesson you'll install it into your virtual environment and move the library window to it, and you'll see how little has to change.

By the end of this lesson you can

  • Install a package into the project's virtual environment, and read the error when it isn't there
  • Swap tkinter widgets for CustomTkinter ones: CTk, CTkFrame, CTkButton and the rest
  • Set the appearance mode and colour theme
  • Say which parts of the app changed and which didn't, and why

Install it

CustomTkinter isn't part of Python: it's a package, made by Tom Schimansky and others, under the MIT licence, which lets anyone use it, governments and businesses included. Install it into the project's virtual environment, as lesson 2.9 installed packages:

Terminal
.venv\Scripts\activate          # on macOS or Linux: source .venv/bin/activate
python -m pip install customtkinter

Use version 6 or newer. Version 6.0 changed a few things that older tutorials get wrong: for one, a button's command now runs when the mouse button is released over it, not when it's pressed, as buttons do everywhere else.

To remember it for next time, add it to pyproject.toml's dependencies, as "customtkinter>=6".

Not in this environment

The wrong way. Open a new terminal, forget to turn the virtual environment on, and run a program that uses CustomTkinter:

Terminal
python hello.py
Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    import customtkinter as ctk
ModuleNotFoundError: No module named 'customtkinter'

You installed it, so why can't Python find it? Because you installed it into .venv, and this terminal runs your system's Python, which has its own separate packages. That's the whole point of a virtual environment (lesson 2.9): each project has its own packages, and nothing leaks between them.

The fix is to turn the environment on, then run the program again. If it still fails, check which Python you're running with python -c "import sys; print(sys.prefix)": it should end in .venv.

You installed a package, but Python says No module named it. What's the likeliest reason?

A first CustomTkinter window

Here's lesson T.1's first window again, in CustomTkinter. Save it as hello.py and run it:

import customtkinter as ctk

ctk.set_appearance_mode("system")
ctk.set_default_color_theme("green")

root = ctk.CTk()
root.title("Library desk")
ctk.CTkLabel(root, text="Welcome to the library").pack(padx=40, pady=(30, 10))
ctk.CTkButton(root, text="Close", command=root.destroy).pack(pady=(0, 30))
root.mainloop()
A dark window with Welcome to the library and a rounded green Close button
hello.py with CustomTkinter 6.0.0 on Windows 11, set to dark mode.

Compare it with T.1's: tk.Tk() became ctk.CTk(), ttk.Label became ctk.CTkLabel, and ttk.Button became ctk.CTkButton. pack, command= and mainloop() are the same, because CustomTkinter's widgets are tkinter widgets: each class inherits from tkinter's and draws itself differently.

The two lines at the top are new:

  • set_appearance_mode("system") follows your computer's light or dark setting. "light" and "dark" force one.
  • set_default_color_theme("green") colours buttons and switches. "blue" is the default, "dark-blue" is another, and version 6.0 added "gold".

Move the desk window

Now the real app. Here's the reference's CustomTkinter window, library_gui/ctk_app.py. It was checked by hand with CustomTkinter 6.0.0 on Windows 11.

How the reference does it library_gui/ctk_app.py
"""The library desk in CustomTkinter: the same window as tk_app.py, with modern widgets.

Needs CustomTkinter (MIT licence) in your virtual environment:  pip install customtkinter
Run it from the folder that holds library/ and library_gui/:  python -m library_gui.ctk_app

Checked by hand with CustomTkinter 6.0.0 on Windows 11. The course's automatic checks
don't install packages, so they don't run it.
"""
import tkinter as tk

import customtkinter as ctk

from library import sample
from library.storage import JsonStorage
from library_gui.presenter import LibraryPresenter, Message


class DeskWindow(ctk.CTkFrame):
    def __init__(self, root: ctk.CTk, presenter: LibraryPresenter) -> None:
        super().__init__(root)
        self.presenter = presenter
        self.search = tk.StringVar()
        self.member = tk.StringVar(value="Choose a member")
        self.chosen = tk.StringVar()
        self.status = tk.StringVar(value="Choose an item, then lend it or take it back.")
        self.names = {name: member_id for member_id, name in presenter.members()}
        self.build()
        self.search.trace_add("write", lambda *args: self.refresh())
        self.refresh()

    def build(self) -> None:
        # A label, not placeholder_text: a CTkEntry with a textvariable shows no placeholder.
        ctk.CTkLabel(self, text="Search").grid(row=0, column=0, sticky="w", padx=12, pady=(12, 0))
        ctk.CTkEntry(self, textvariable=self.search).grid(
            row=1, column=0, columnspan=3, sticky="ew", padx=12
        )
        # CustomTkinter has no table, so each item is a radio button in a scrolling list.
        self.table = ctk.CTkScrollableFrame(self, height=260)
        self.table.grid(row=2, column=0, columnspan=3, sticky="nsew", padx=12, pady=12)
        ctk.CTkOptionMenu(self, variable=self.member, values=list(self.names)).grid(
            row=3, column=0, sticky="ew", padx=(12, 0)
        )
        ctk.CTkButton(self, text="Lend", command=self.lend).grid(row=3, column=1, padx=12)
        ctk.CTkButton(self, text="Return", command=self.give_back).grid(
            row=3, column=2, padx=(0, 12)
        )
        ctk.CTkLabel(self, textvariable=self.status).grid(
            row=4, column=0, columnspan=3, sticky="w", padx=12, pady=12
        )
        self.columnconfigure(0, weight=1)
        self.rowconfigure(2, weight=1)

    def refresh(self) -> None:
        """Empties the list and fills it again from the presenter."""
        for widget in self.table.winfo_children():
            widget.destroy()
        for row in self.presenter.rows(self.search.get()):
            text = f"{row.title}  ·  {row.kind}  ·  {row.state}"
            if row.due:
                text += f"  ·  due {row.due}"
            ctk.CTkRadioButton(
                self.table, text=text, variable=self.chosen, value=row.item_id
            ).pack(anchor="w", pady=4)

    def lend(self) -> None:
        member_id = self.names.get(self.member.get(), "")
        self.show(self.presenter.lend(self.chosen.get(), member_id))

    def give_back(self) -> None:
        self.show(self.presenter.give_back(self.chosen.get()))

    def show(self, message: Message) -> None:
        self.status.set(message.text)
        self.refresh()


def main(path: str = "library.json") -> None:
    storage = JsonStorage(path)
    library = storage.load()
    if not len(library.catalogue):
        sample.fill(library)
    ctk.set_appearance_mode("system")
    ctk.set_default_color_theme("green")
    root = ctk.CTk()
    root.title("Library desk")
    root.minsize(600, 420)
    window = DeskWindow(root, LibraryPresenter(library, storage))
    window.grid(row=0, column=0, sticky="nsew", padx=12, pady=12)
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    root.mainloop()


if __name__ == "__main__":
    main()
Terminal
python -m library_gui.ctk_app
The CustomTkinter desk in light mode: a search box, items as radio buttons with Emma chosen, a member drop-down, Lend and Return buttons, and a refusal message Light
The same desk in dark mode Dark
The desk after lending Dune to Sam and trying to lend the Atlas, with the green theme.

Put it next to tk_app.py and compare. What changed:

  • The window's parent class: ctk.CTkFrame instead of ttk.Frame.
  • The widgets: CTkEntry, CTkOptionMenu (a drop-down) and CTkLabel.
  • The table. CustomTkinter has no table widget, so each item is a CTkRadioButton in a CTkScrollableFrame. All the buttons share one variable, self.chosen, and picking one sets it to that item's id. The other way is to keep ttk.Treeview, styled to match.
  • The dialog: the status line shows refusals, so show lost its messagebox.
  • The search box has a label above it. A CTkEntry can show grey placeholder text with placeholder_text=, but not while it has a textvariable, so a label does that job.

What didn't change: grid and sticky, StringVar and trace_add, the order of every method, and all of presenter.py and its tests. The model and the presenter don't know the window was swapped. That's the payoff for lesson T.4's split.

Check

Why do pack, grid and StringVar all work with CustomTkinter?
Moving the window to CustomTkinter, which file changed?
CustomTkinter has no table. How does the reference show the catalogue?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python