打开具有不同主题的顶层时如何维护tkinter主题

时间:2019-01-17 12:15:39

标签: python tkinter styles themes

我的tkinter root windowtoplevel window具有不同的主题,但是当我打开toplevel window时,它将root window更改为为toplevel window设置的主题< / p>

我想维护每个窗口的主题集。当我关闭顶层窗口并再次打开它时,这会导致错误_tkinter.TclError: Theme MyStyle already exists

import tkinter as tk
import tkinter.ttk as ttk



def test2():
    rt1 = tk.Toplevel()
    rt1.geometry("500x500")

    s = ttk.Style()
    s.theme_create("MyStyle", parent="alt", settings={
    "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0]}},
    "TNotebook.Tab": {"configure": {"padding": [50, 8] }}})

    s.theme_use("MyStyle")

    notebook = ttk.Notebook(rt1)

    f1 = tk.Frame(notebook, width=200, height=200)
    f2 = tk.Frame(notebook, width=200, height=200)

    notebook.add(f1, text="tab 1")
    notebook.add(f2, text="tab 2")

    notebook.grid(row=0, column=0, sticky="nw")


root = tk.Tk()
root.geometry("500x500")


tree = ttk.Treeview(root, column=("col1", "col2"))
tree.insert("", tk.END, values=("deee", "fjfj","fjjf", "jfjfjf"))
tree.pack()

b3 = tk.Button(root, text="new", command=test2)
b3.place(x=200, y=200)


root.mainloop()

1 个答案:

答案 0 :(得分:1)

现在,您正试图在每次按下按钮时创建样式,这就是导致问题的原因。

相反,只需将主题创建移动到全局名称空间即可在其中创建一次,而不再是一个问题。

import tkinter as tk
import tkinter.ttk as ttk


def test2():
    rt1 = tk.Toplevel()
    rt1.geometry("500x500")
    notebook = ttk.Notebook(rt1)
    f1 = tk.Frame(notebook, width=200, height=200)
    f2 = tk.Frame(notebook, width=200, height=200)
    notebook.add(f1, text="tab 1")
    notebook.add(f2, text="tab 2")
    notebook.grid(row=0, column=0, sticky="nw")

root = tk.Tk()
root.geometry("500x500")
tree = ttk.Treeview(root, column=("col1", "col2"))
tree.insert("", tk.END, values=("deee", "fjfj","fjjf", "jfjfjf"))
tree.pack()

s = ttk.Style()
s.theme_create("MyStyle", parent="alt", settings={
"TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0]}},
"TNotebook.Tab": {"configure": {"padding": [50, 8] }}})
s.theme_use("MyStyle")

b3 = tk.Button(root, text="new", command=test2)
b3.place(x=200, y=200)
root.mainloop()