我正在使用 Tkinter 和 ttk 在 Python 中创建 GUI。我想为用户可以配置的 UI 设置两个单独的主题。这些选项之一是使用以下代码调用的 vista 主题:
from tkinter import Tk
from tkinter.ttk import Style
root = Tk()
root.style = Style()
root.style.theme_use('vista')
另一种选择是 black 主题,调用时使用:
from tkinter import Tk
from ttkthemes import ThemedStyle
root = Tk()
root.style = ThemedStyle()
root.style.theme_use('black')
我遇到了一些问题,因为我希望用户能够在程序运行时切换主题。单独应用这些主题(即应用一个主题,关闭程序并在启动时应用其他主题)效果很好。当从 vista 切换时,我开始在代码后面的某处调用 主题到 root.style = ThemedStyle() 后跟 root.style = Style() 时遇到问题black 主题:
if self.ui_theme == 'Dark':
self.root.style = ThemedStyle()
theme = 'black'
self.root.tk_setPalette(background='#2f3136')
else:
self.root.style = Style()
theme = 'vista'
self.root.tk_setPalette(background='#f0f0f0')
self.root.style.theme_use(theme)
最重要的是,从 black 到 vista 再回到 black 会再次导致以下错误:
error reading package index file C:/Python34/Lib/site-packages/ttkthemes/themes/pkgIndex.tcl: Theme plastik already exists
我假设在同一实例中两次调用 self.root.style = ThemedStyle() 时会发生这种情况。
有没有办法在不强制用户在应用新主题时重新启动应用程序的情况下解决这个问题?提前致谢。
请您参考如下方法:
仅在开始时创建一次 Style() 和 ThemeStyle() 并分配给变量。
然后将变量分配给 root.style。
from tkinter import Tk
from tkinter.ttk import Style, Button
from ttkthemes import ThemedStyle
def style_1():
print('winxpblue')
root.style = s
root.style.theme_use('winxpblue')
def style_2():
print('black')
root.style = t
root.style.theme_use('black')
root = Tk()
s = Style()
t = ThemedStyle()
#print(s.theme_names())
#print(t.theme_names())
Button(root, text="winxpblue", command=style_1).pack()
Button(root, text="black", command=style_2).pack()
root.mainloop()
编辑: 在 Linux 上测试后,我发现我不需要 Style()。我在 ThemedStyle() 中拥有所有主题。也许在 Windows/MacOS 上它的工作方式相同。
import tkinter as tk
from tkinter import ttk
import ttkthemes
root = tk.Tk()
root.style = ttkthemes.ThemedStyle()
for i, name in enumerate(sorted(root.style.theme_names())):
b = ttk.Button(root, text=name, command=lambda name=name:root.style.theme_use(name))
b.pack(fill='x')
root.mainloop()
