gpt4 book ai didi

python - 在简单的 Python Tkinter 程序中使用开/关功能实现暗模式?

转载 作者:行者123 更新时间:2023-12-05 02:08:46 24 4
gpt4 key购买 nike

我按照本教程使用 Python 的 Tkinter 创建了一个非常简单的文本编辑器应用程序。我想做的是添加使用 checkbutton 的选项,所以当 checked 时,文本编辑器的主题将更改为暗模式主题,当 >未选中,将返回默认的白色主题。我该怎么做?

我尝试将函数绑定(bind)到 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()

最佳答案

你可以通过安装模块 ttkthemes 来做

pip 安装 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()

关于python - 在简单的 Python Tkinter 程序中使用开/关功能实现暗模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60595078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com