繁体   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