簡體   English   中英

Tkinter - 當我有不同類型的類時,如何正確使用“ttk.style()”語句?

[英]Tkinter - How can I use correctly the "ttk.style()" statement when I have different kind of classes?

在我的真實代碼中,我有一個主窗口,用戶可以在其中選擇打開其他類型的窗口。 在主要內容中,我使用ttk.style()語句定義了ttk樣式。 它有效,但如果我在專用於其他窗口的其他類中定義相同的樣式,則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類中的窗口不像MainWindow類中的另一個那樣使用自定義ttk樣式?

然后我只想寫一次ttk指令,因為在我的真實代碼中,所有類都使用相同的樣式。 最好的方法是什么?

以下是有關我的示例的屏幕截圖: 在此處輸入圖片說明

Tk每個實例都是一個單獨的環境,不能與Tk其他實例共享數據。 如果您希望多個窗口能夠與第一個窗口共享信息,則必須創建Toplevel而不是Tk實例。

您的第二個窗口不接受新樣式的原因是您創建的Style對象屬於原始根窗口。 如果您希望它影響新的根窗口,您必須通過指定master屬性明確地告訴它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM