Tkinter ttkbootstrap OptionMenu Widget Tutorial

The ttkbootstrap OptionMenu widget provides a stylish dropdown selection menu that integrates seamlessly with theme-aware color palettes (`bootstyle`) and tracking variables.

Tutorial Breakdown:

Part I: Basic OptionMenu Setup & Bootstyle Colors

ttkbootstrap OptionMenu Basic We tracked selection using StringVar and used Pack layout manager.
OptionMenu supports bootstyle=SUCCESS to color-code dropdown toggle actions.

import ttkbootstrap as ttk
from ttkbootstrap.constants import *

def on_select(val):
    lbl_status.config(text=f"Selected Option: {val}")

app = ttk.Window(title="OptionMenu Demo", themename="flatly")
app.geometry("400x220")

selected_var = ttk.StringVar(value="Python")
options = ["Python", "JavaScript", "PHP", "C++"]

# OptionMenu widget with success bootstyle
opt_menu = ttk.OptionMenu(
    app,
    selected_var,
    "Python",
    *options,
    command=on_select,
    bootstyle=SUCCESS
)
opt_menu.pack(padx=20, pady=25, fill=X)

lbl_status = ttk.Label(app, text="Selected Option: Python", font=("Helvetica", 11, "bold"), bootstyle=INFO)
lbl_status.pack(padx=20, pady=10)

app.mainloop()
Practical Overview

The ttkbootstrap OptionMenu widget is a compact dropdown list selector. By applying bootstyle properties, developers can style the menu button to match contextual color themes across the application.

Part II: Live Dynamic Theme Switcher

ttkbootstrap OptionMenu Theme Switcher We used StringVar to track themes and used Grid layout manager.
Selecting theme radio buttons applies runtime updates across the application window via app.style.theme_use().

import ttkbootstrap as ttk
from ttkbootstrap.constants import *

def change_theme():
    selected_theme = theme_var.get()
    app.style.theme_use(selected_theme)
    label_info.config(text=f"Active Theme: {selected_theme}")

app = ttk.Window(title="OptionMenu Theme Switcher", themename="superhero")
app.geometry("460x260")

theme_var = ttk.StringVar(value="superhero")
themes = ["cosmo", "flatly", "superhero", "darkly"]

lbl_title = ttk.Label(app, text="Select Application Theme:", font=("Helvetica", 11, "bold"))
lbl_title.grid(row=0, column=0, columnspan=4, padx=15, pady=10, sticky="w")

for idx, t_name in enumerate(themes):
    rb = ttk.Radiobutton(
        app,
        text=t_name.capitalize(),
        value=t_name,
        variable=theme_var,
        command=change_theme,
        bootstyle="outline-toolbutton"
    )
    rb.grid(row=1, column=idx, padx=5, pady=5)

opt_widget = ttk.OptionMenu(app, ttk.StringVar(value="Option A"), "Option A", "Option A", "Option B", "Option C", bootstyle=WARNING)
opt_widget.grid(row=2, column=0, columnspan=4, padx=15, pady=20, sticky="ew")

label_info = ttk.Label(app, text="Active Theme: superhero", bootstyle=SUCCESS, font=("Helvetica", 10))
label_info.grid(row=3, column=0, columnspan=4, padx=15, pady=5)

app.mainloop()

Part III: SQLite Database Integration (Saving Selected Option)

ttkbootstrap OptionMenu Database Integration We used SQLite database and SQLAlchemy to persist the selected choice.
Upon startup, the OptionMenu loads its default value from SQLite and commits updates when saved.

1️⃣ Creating SQLite Table & Inserting Default Setting

from sqlalchemy import create_engine, text

# Use raw strings r"..." to prevent Unicode escape errors in Windows paths
DATABASE_URL = r"sqlite:///I:\My Drive\testing3\ttkbootstrap\preferences_db.db"
engine = create_engine(DATABASE_URL, echo=False)

with engine.connect() as connection:
    connection.execute(text("CREATE TABLE IF NOT EXISTS preferences (id INTEGER PRIMARY KEY, pref_key TEXT UNIQUE NOT NULL, pref_value TEXT NOT NULL)"))
    
    result = connection.execute(text("SELECT COUNT(*) FROM preferences WHERE pref_key='preferred_language'"))
    if result.scalar() == 0:
        connection.execute(text("INSERT INTO preferences (pref_key, pref_value) VALUES ('preferred_language', 'Python')"))
        connection.commit()

print("Preferences database initial setup completed.")

2️⃣ Dynamic GUI Syncing OptionMenu with SQLite via SQLAlchemy

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from sqlalchemy import create_engine, text

DATABASE_URL = r"sqlite:///I:\My Drive\testing3\ttkbootstrap\preferences_db.db"
engine = create_engine(DATABASE_URL, echo=False)
connection = engine.connect()

def get_stored_preference():
    res = connection.execute(text("SELECT pref_value FROM preferences WHERE pref_key='preferred_language'"))
    row = res.fetchone()
    return row[0] if row else "Python"

def save_preference_db():
    val = opt_var.get()
    connection.execute(
        text("UPDATE preferences SET pref_value = :val WHERE pref_key='preferred_language'"),
        {"val": val}
    )
    connection.commit()
    lbl_status.config(text=f"Saved to DB: {val}")

root = ttk.Window(title="OptionMenu SQLite Sync", themename="flatly")
root.geometry("420x240")

init_val = get_stored_preference()
opt_var = ttk.StringVar(value=init_val)
choices = ["Python", "JavaScript", "PHP", "C++"]

opt_menu = ttk.OptionMenu(root, opt_var, init_val, *choices, bootstyle=PRIMARY)
opt_menu.pack(padx=20, pady=20, fill=X)

btn_save = ttk.Button(root, text="Save Preference", command=save_preference_db, bootstyle=SUCCESS)
btn_save.pack(pady=5)

lbl_status = ttk.Label(root, text=f"Loaded from DB: {init_val}", bootstyle=INFO, font=("Helvetica", 10))
lbl_status.pack(pady=10)

root.mainloop()
connection.close()

Part IV: Connecting to MySQL using SQLAlchemy

To connect your OptionMenu preference tracker to a centralized MySQL database server, update the SQLAlchemy connection string:

# SQLite Connection (Commented Out)
# DATABASE_URL = r"sqlite:///I:\My Drive\testing3\ttkbootstrap\preferences_db.db"

# MySQL Connection string using PyMySQL
DATABASE_URL = "mysql+pymysql://username:password@localhost/student_db"

engine = create_engine(DATABASE_URL, echo=False)

Common Errors & Troubleshooting

Issue / Error Cause Recommended Solution
OptionMenu selection doesn't update StringVar Passing values incorrectly without unpacking or mismatching string variables. Ensure the same StringVar instance is passed to both the OptionMenu and checked via .get().
Dropdown items truncation Menu width is constrained by initial option text length. Set a minimum width or apply fill=X when packing the OptionMenu widget.

Frequently Asked Questions

Clear the menu's internal menu children via menu = opt_menu["menu"]; menu.delete(0, "end") and re-append new option choices.

Yes! Pass the default placeholder string as the third positional argument in ttk.OptionMenu(root, var, "Select Option...", *choices).



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer