如何在简单的Python Tkinter程序中实现带有开/关功能的暗黑模式?

3
我在使用Python的Tkinter创建一个非常简单的文本编辑器应用程序时,遵循了这个教程。我想做的是添加使用checkbutton的选项,因此当选中时,文本编辑器的主题将更改为暗模式主题,当取消选中时,将返回默认的白色主题。我该怎么做?
我尝试将函数绑定到checkbutton上,在其中检查状态,并根据状态更改窗口中框架的变量。例如,如果它是:
frame = tk.Frame(colour=white)

作为默认值,在函数内我会输入以下内容:
frame = tk.Frame(colour=white)

即使对我来说,这看起来也不正确。(我知道格式不正确。)

这里是代码(没有我的黑暗模式尝试):

import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename

def open_file():
    """Open a file for editing."""
    filepath = askopenfilename(
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
    )
    if not filepath:
        return
    txt_edit.delete(1.0, tk.END)
    with open(filepath, "r") as input_file:
        text = input_file.read()
        txt_edit.insert(tk.END, text)
    window.title(f"Simple Text Editor - {filepath}")

def save_file():
    """Save the current file as a new file."""
    filepath = asksaveasfilename(
        defaultextension="txt",
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
    )
    if not filepath:
        return
    with open(filepath, "w") as output_file:
        text = txt_edit.get(1.0, tk.END)
        output_file.write(text)
    window.title(f"Simple Text Editor - {filepath}")

window = tk.Tk()
window.title("Simple Text Editor")
window.rowconfigure(0, minsize=800, weight=1)
window.columnconfigure(1, minsize=800, weight=1)

txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)
btn_open = tk.Button(fr_buttons, text="Open", command=open_file)
btn_save = tk.Button(fr_buttons, text="Save As...", command=save_file)

btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
btn_save.grid(row=1, column=0, sticky="ew", padx=5)

fr_buttons.grid(row=0, column=0, sticky="ns")
txt_edit.grid(row=0, column=1, sticky="nsew")

window.mainloop()

这个回答解决了你的问题吗?Python tkinter时钟的日间主题和夜间主题 - stovfl
3个回答

4

通过安装ttkthemes模块,您可以进行以下操作

pip install ttkthemes

import tkinter as tk
import tkinter.ttk as ttk 
from ttkthemes import ThemedStyle

app = tk.Tk()
app.geometry("200x400")
app.title("Changing Themes")
# Setting Theme
style = ThemedStyle(app)
style.set_theme("scidgrey")

# Button Widgets
Def_Btn = tk.Button(app,text='Default Button')
Def_Btn.pack()
Themed_Btn = ttk.Button(app,text='Themed button')
Themed_Btn.pack()

# Scrollbar Widgets
Def_Scrollbar = tk.Scrollbar(app)
Def_Scrollbar.pack(side='right',fill='y')
Themed_Scrollbar = ttk.Scrollbar(app,orient='horizontal')
Themed_Scrollbar.pack(side='top',fill='x')

# Entry Widgets
Def_Entry = tk.Entry(app)
Def_Entry.pack()
Themed_Entry = ttk.Entry(app)
Themed_Entry.pack()

app.mainloop()

我认为他想在暗模式和正常模式之间切换。 - Delrius Euphoria
@CoolCloud 好的:) - Belgin Android

1
我们可以在类的一个方法中创建GUI。然后,我们可以定义另一个方法来关闭GUI,更改设置主题参数的变量,然后重新启动GUI。
这可能看起来像是很多代码,但一旦设置好了,它就非常可扩展,并且不仅适用于颜色,还适用于其他属性。您可以遍历所有适当的小部件。
请查看以下代码:
import tkinter as tk


class App():
    # Here, set everything up you want to override later, when restarting the GUI
    def __init__(self):
        self.color_scheme('dark')  # This determines the mode the GUI starts up in.
        self.font = ('Serif', 12)
        # This will be shown on the button (when dark mode is active it needs to say "light theme")
        self.theme_btn_text = 'Light Theme'

        self.mainGUI()  # Call the actual GUI and Inistialize with the standard Settings. This has to be AFTER all the setup

    def mainGUI(self):
        # Set up Root window
        self.root = tk.Tk()
        self.root.title('A title')
        # whenever we style items, we use the attributes as colors. These attributes are defined in the function below.
        self.root.configure(bg=self.bg)

        # Set up buttons (only the unique elements)
        self.btn1 = tk.Button(self.root,
                              text='Random Text')

        self.theme_btn = tk.Button(self.root,
                                   text=self.theme_btn_text,
                                   command=lambda: self.theme_switch())

        # Set up the attributes that all buttons have in common and pack them (or better use grid)
        # Style them however you want
        for btn in [self.btn1, self.theme_btn]:
            btn.configure(bg=self.bg,
                          fg=self.fg,
                          activebackground=self.bg,
                          borderwidth=0)
            btn.pack(padx=20, pady=20)
        # Don't forget that everything needs to be between the TK() and the mainloop()
        self.root.mainloop()

    # Create the method that sets the colours of the class, depending on the active theme.
    # This is used in the __init__ method to create the first theme, but also by the theme_switch method below.
    def color_scheme(self, mode):
        if mode == 'dark':
            self.bg, self.fg, self.ac1, self.ac2 = ('#282828', 'white', '#404040y', '#B3B3B3')
        if mode == 'light':
            self.bg, self.fg, self.ac1, self.ac2 = ('#FBF8F1', 'black', '#F7ECDE', '#E9DAC1')

    # This could of course also be placed inside the theme_switch method directly. But I like to use it for other things too.
    def restart_GUI(self):
        self.root.destroy()
        self.mainGUI()

    # Here we decide on whether we need to switch from light to dark or the other way around by looking at the color used at the moment the method is called via button press
    def theme_switch(self):
        if self.bg == '#282828':
            self.color_scheme('light')
            # We change the text to match the opposite theme
            self.theme_btn_text = 'Dark Theme'
        elif self.bg == '#FBF8F1':
            self.color_scheme('dark')
            self.theme_btn_text = 'Light Theme'
        self.restart_GUI()


# Finally, we initiate an object of our class to start the GUI
x = App()


希望这能对某些人有所帮助!当然,这两种方法可以轻松结合起来,扩展到其他属性和其他小部件等。
祝一切顺利!

0
我想要做的是添加使用复选框的选项,这样当选中时,文本编辑器的主题将更改为暗模式主题,而取消选中时则更改回白色主题。
更简单的方法是只需使用一个快捷键即可在黑色和白色之间切换。使用一个复选框,因此您不需要额外的小部件。
  • 添加了tk.IntVar()用于checkbox
  • 添加了ttk.Checkbutton小部件。
  • 添加了方法函数。
  • 在方法函数中添加了.config
片段:
import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename, asksaveasfilename

def open_file():
    """Open a file for editing."""
    filepath = askopenfilename(
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
    )
    if not filepath:
        return
    txt_edit.delete(1.0, tk.END)
    with open(filepath, "r") as input_file:
        text = input_file.read()
        txt_edit.insert(tk.END, text)
    window.title(f"Simple Text Editor - {filepath}")

def save_file():
    """Save the current file as a new file."""
    filepath = asksaveasfilename(
        defaultextension="txt",
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
    )
    if not filepath:
        return
    with open(filepath, "w") as output_file:
        text = txt_edit.get(1.0, tk.END)
        output_file.write(text)
    window.title(f"Simple Text Editor - {filepath}")

window = tk.Tk()
window.title("Simple Text Editor")
window.rowconfigure(0, minsize=800, weight=1)
window.columnconfigure(1, minsize=800, weight=1)

check_on = tk.IntVar()

def toggle():
    if check_on.get():
        cb_on.config(text='I love Python ')
        txt_edit.config(fg='white', bg="#26242f")
        cb_on.config(text='Change To White-mode')
    else:
        txt_edit.config(fg='black', bg="white")
        cb_on.config(text='Change To Dark-mode')
     

txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2)
btn_open = tk.Button(fr_buttons, text="Open", command=open_file)
btn_save = tk.Button(fr_buttons, text="Save As...", command=save_file)
cb_on = ttk.Checkbutton(fr_buttons, text='Change To Dark-mode',
                        variable=check_on, onvalue=1,
                        offvalue=0, command=toggle)


btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5)
btn_save.grid(row=1, column=0, sticky="ew", padx=5)
cb_on.grid(row=2, column=0, sticky="ew", padx=5, pady=5 )

fr_buttons.grid(row=0, column=0, sticky="ns")
txt_edit.grid(row=0, column=1, sticky="nsew")
 

window.mainloop()

截图:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接