首页 > 解决方案 > Tkinter - 当我有不同类型的类时,如何正确使用“ttk.style()”语句?

问题描述

在我的真实代码中,我有一个主窗口,用户可以在其中选择打开其他类型的窗口。在主要的部分中,我使用语句定义了ttk样式。ttk.style()它可以工作,但是如果我在其他专用于其他窗口的其他类中定义相同的样式,ttk.style()则不再起作用。为什么?下面是一个例子:

from tkinter import *
from tkinter import ttk

class MainWindow:
    def __init__(self):

        self.parent=Tk()
        self.parent.geometry("400x400")
        self.parent.title(self.main_name)
        self.parent.configure(background="#f0f0f0")

        style=ttk.Style()
        style.configure("TButton", background="red", padding=0)

        MyButton=ttk.Button(self.parent, text="open a new window", command=self.Open)
        MyButton.pack()

        self.parent.mainloop()

    def Open(self):
        obj=NewWindow()

class NewWindow():
    def __init__(self):

        self.parent=Tk()
        self.parent.geometry("400x400")
        self.parent.configure(background="#f0f0f0")

        style=ttk.Style()
        style.configure("TButton", background="red", padding=0)
    
        MyButton=ttk.Button(self.parent, text="This button has not a custom style.. why?")
        MyButton.pack()

if __name__=="__main__":
    app=MainWindow()

为什么类中的窗口NewWindow不像类中的其他窗口那样使用自定义ttk样式MainWindow

然后我想只写一次ttk指令,因为在我的真实代码中,所有类都使用相同的样式。最好的方法是什么?

下面是关于我的示例的屏幕截图: 在此处输入图像描述

标签: pythontkinterstylesttk

解决方案


的每个实例Tk都是一个单独的环境,并且不能与 的其他实例共享数据Tk。如果您希望多个窗口能够与第一个窗口共享信息,您必须创建实例Toplevel而不是Tk.

您的第二个窗口不接受新样式的原因是Style您创建的对象属于原始根窗口。如果您希望它影响新的根窗口,您必须通过指定master属性明确告诉它。

style=ttk.Style(master=self.parent)

推荐阅读