I’m trying to have a program change from light to dark mode with a check button but it does not change the theme
import tkinter as tk
import ttkbootstrap as ttk
#setup
window = ttk.Window(themename = "flatly")
window.title("Buttons")
window.geometry('600x400')
#dark mode
check_var = tk.StringVar()
check = ttk.Checkbutton(
window,
text= "Dark mode",
command= lambda: print(check_var.get()),
variable= check_var)
check.pack()
if check_var == 1:
window = ttk.Window(themename = "darkly")
if check_var == 0:
window = ttk.Window(themename = "flatly")
#run
window.mainloop()
I want the theme to go from to light to dark when the check button is pressed
You need to check the state of the checkbutton inside the callback of command
option instead of after creating the checkbutton. Also you need to use theme_use()
of Style
object (window.style
) to change theme:
...
def change_theme():
theme = 'darkly' if check_var.get() == '1' else 'flatly'
window.style.theme_use(theme)
...
check = ttk.Checkbutton(
window,
text="Dark mode",
command=change_theme,
variable=check_var)
...
You need to create function of Checkbutton class. We can set variable, style and command.
snippet:
check = ttk.Checkbutton(
window,
text= "Dark mode",
command= lambda:toggle_theme(check_var),
variable= check_var,
style='custom.TCcheckbutton')
check.pack()
def toggle_theme(check_var):
try:
if check_var.get():
ttk.Window(themename = "darkly")
else:
ttk.Window(themename = "flatly")
except:
pass
You want to change theme of the same window and not to open a new window with different theme. So,
-
use
ttk.Style().theme_use("<theme_name>")
. -
use
IntVar()
instead ofStringVar()
asIntVar
has only two states 0 and 1. -
Use a separate function and change the theme using
ttk.Style().theme_use("<theme_name>")
-
add
variable= int_variable_name
as an argument of the widget Checkbuttonimport tkinter as tk import ttkbootstrap as ttk def change_theme(): # use function check_state = check_var.get() if check_state == 1: style.theme_use("darkly") # use style.theme_use else: style.theme_use(themename = "flatly") #setup window = ttk.Window("flatly") window.title("Buttons") window.geometry('600x400') style = ttk.Style() style.theme_use("flatly") # use style.theme_use check_var = tk.IntVar() # use IntVar check = tk.Checkbutton(window, text= "Dark mode", variable=check_var, command = change_theme) # use variable = check_var as an argument check.pack() window.mainloop()
`