如何更改 ttk 比例滑块的颜色?

时间:2021-03-26 10:31:33

标签: python ttk

这是代码片段:

self.slider_song = ttk.Scale(self.controlsFrame,
                                     length=300,
                                     style='songSlider.Horizontal.TScale',
                                     from_=0,
                                     to=100,
                                     orient=tk.HORIZONTAL,
                                     value=0,
                                     command=self.change_song_pos)

def __configure_scale_style(self):
    self.scaleStyle.configure("songSlider.Horizontal.TScale", background='#FFDB00')

它适用于背景颜色,但我在任何地方都找不到更改滑块(您拉的东西)颜色的选项。

1 个答案:

答案 0 :(得分:0)

我们的想法是:

为滑块创建所需颜色的图像,例如与 tk.PhotoImage:

img_slider = tk.PhotoImage(width=30, height=15)
img_slider.put("{<pixel_color> ... <pixel_color>} {<second line>} ...")

我使用了一个基本的矩形,但如果您愿意,您也可以加载更精细的图像。

创建彩色滑块主题元素:

style.element_create('custom.Horizontal.Scale.slider', 'image', img_slider,
                     ('active', img_slider_active))

我还使用了不同的图像 img_slider_active,以在光标位于滑块上时突出显示滑块。

在自定义样式中使用新元素

style.layout('custom.Horizontal.TScale',
             [('Horizontal.Scale.trough',
               {'sticky': 'nswe',
                'children': [('custom.Horizontal.Scale.slider',
                              {'side': 'left', 'sticky': ''})]})])

将自定义样式应用于您的 TickScale 小部件。由于 TickScale 是基于 ttk.Scale 的,因此需要使用样式来设置背景、前景和槽色选项,请参阅下面的完整代码。

import tkinter as tk
from tkinter import ttk
from ttkwidgets import TickScale

def set_img_color(img, color):
    """Change color of PhotoImage img."""
    pixel_line = "{" + " ".join(color for i in range(img.width())) + "}"
    pixels = " ".join(pixel_line for i in range(img.height()))
    img.put(pixels)

root = tk.Tk()
# create images used for the theme
slider_width = 30
slider_height = 15
# normal slider
img_slider = tk.PhotoImage('img_slider', width=slider_width, height=slider_height, master=root)
set_img_color(img_slider, "red")
# active slider
img_slider_active = tk.PhotoImage('img_slider_active', width=slider_width, height=slider_height, master=root)
set_img_color(img_slider_active, '#1065BF')

style = ttk.Style(root)
style.theme_use('clam')
# create scale element
style.element_create('custom.Horizontal.Scale.slider', 'image', img_slider,
                     ('active', img_slider_active))
# create custom layout
style.layout('custom.Horizontal.TScale',
             [('Horizontal.Scale.trough',
               {'sticky': 'nswe',
                'children': [('custom.Horizontal.Scale.slider',
                              {'side': 'left', 'sticky': ''})]})])
style.configure('custom.Horizontal.TScale', background='black', foreground='grey',
                troughcolor='#73B5FA')
scale = TickScale(root, from_=0, to=100, tickinterval=100, orient="horizontal",
                  style='custom.Horizontal.TScale')
scale.pack(fill='x')
root.mainloop()