簡體   English   中英

更改 Tkinter Scale 的 ttk 樣式布局中的元素

[英]Change element in ttk Style layout of Tkinter Scale

我有一個關於 ttk 樣式的問題。 我正在將自定義樣式應用於 tkinter 比例。 具體來說,這意味着,我使用圖像作為滑塊。

現在,我想創建三個不同的比例,其中滑塊的顏色不同。 我將三個 pyimages 存儲在列表self.slider = [pyimage0, pyimage1, pyimage2]

開始 ttk 樣式:

style = ttk.Style()

style.element_create('custom.Scale.trough', 'image', self.trough)
style.element_create('custom.Scale.slider', 'image', self.slider[0])

style.layout('custom.Horizontal.TScale',
              [('custom.Scale.trough', {'sticky': 'we'}),
               ('custom.Scale.slider',
                {'side': 'left', 'sticky': '',
                 'children': [('custom.Horizontal.Scale.label', {'sticky': ''})]
                })])
style.configure('custom.Horizontal.TScale', background='#ffffff')

現在我想在需要時簡單地通過彩色滑塊進行更改。 但是,如何在樣式中創建元素后更改滑塊圖像?

我試過:

style.configure('custom.Horizontal.TScale.custom.Scale.slider', image=self.slider[i])

但它只是停留在self.slider[0]

問候和感謝!!

編輯

class CustomScale(ttk.Scale):
    def __init__(self, master=None, **kw):
        kw.setdefault("orient", "horizontal")
        self.variable = kw.pop('variable', DoubleVar(master))
        ttk.Scale.__init__(self, master, variable=self.variable, **kw)
        self._style_name = '{}.custom.{}.TScale'.format(self, kw['orient'].capitalize()) # unique style name to handle the text
        self['style'] = self._style_name

您需要單獨定義每個樣式,以便它們具有自己的唯一名稱。

名稱是完全任意的,我不得不使用自己的圖像,但它有效。

我已經擴展了答案以演示用法。


for i,a in enumerate(["red", "green", "blue"]):

    style.element_create(f'{a}.Scale.trough', 'image', self.trough)
    style.element_create(f'{a}.Scale.slider', 'image', self.slider[i])

    style.layout(f'{a}.Horizontal.TScale',
                  [(f'{a}.Scale.trough', {'sticky': 'we'}),
                   (f'{a}.Scale.slider',
                    {'side': 'left', 'sticky': '',
                     'children': [(f'{a}.Horizontal.Scale.label', {'sticky': ''})]
                    })])
    style.configure(f'{a}.Horizontal.TScale', background='#ffffff')

self.redslider = ttk.Scale(self.master, from_ = 0, to=255, style = "red.Horizontal.TScale")
self.redslider.grid(row = 0, column = 0, sticky = tk.NSEW)

暫無
暫無

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

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