使用按钮更改主题 - python Tkinter

问题描述 投票:0回答:1

我正在尝试使用复选按钮将程序从浅色模式更改为深色模式,但它不会改变主题

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()

我希望当按下复选按钮时主题从浅色变为深色

python python-3.x tkinter themes
1个回答
0
投票

您需要在

command
选项的回调中检查复选按钮的状态,而不是在创建复选按钮之后。 您还需要使用
theme_use()
对象 (
Style
) 的
window.style
来更改主题:

...

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)
...
© www.soinside.com 2019 - 2024. All rights reserved.