簡體   English   中英

在 tkinter 中更改滾動條的外觀(使用 ttk 樣式)

[英]Changing the appearance of a Scrollbar in tkinter (using ttk styles)

我想知道你是否可以幫助我解決 ttk 中的樣式選項問題。 我已經設法將大部分基本的 ttk 小部件更改為我喜歡的樣式。 我只是停留在改變滾動條的樣式上。 我已經搜索了幾個小時尋找答案,不幸的是無濟於事。

下面是使用滾動條樣式選項的示例代碼:

import tkinter as tk                 
from tkinter import ttk

class Gui:
    def __init__(self,mainframe):

        #set the style
        style = ttk.Style()
        style.configure('Horizontal.TScrollbar',background = "blue" )   

        #Create a mainframe
        self.mainframe = mainframe
        self.mainframe.title("example")


        #creating scrollbar frame
        scrl_attr_frame = ttk.Frame(self.mainframe)                            
        scrl_attr_frame.grid(column=0,row=5,sticky="ns")                                           
        scrl_attr_frame.rowconfigure(0, weight=1)                                                   
        attr_canvas = tk.Canvas(scrl_attr_frame)                                                   
        h_scroll = ttk.Scrollbar(scrl_attr_frame,orient="horizontal", command=attr_canvas.xview)
        attr_canvas.configure(xscrollcommand=h_scroll.set)                                       
        attr_canvas.grid(column=0,row=0,sticky="ns")                                                                            
        h_scroll.grid(column=0, row=1,sticky="we") 
        attr_frame = ttk.Frame(attr_canvas)                                                        
        attr_frame.grid(column=0,row=0,sticky="ns")                                                 
        attr_canvas.create_window((0,0),window=attr_frame, anchor='nw')
        attr_frame.bind("<Configure>",lambda event, canvas=attr_canvas : canvas.configure(scrollregion=canvas.bbox("all"),width=200,height=200,takefocus=False,highlightthickness=0))#attribute_frame.winfo_height()/20,highlightthickness=0))

        #setup treeview widget
        tree_columns = ("c1", "c2", "c3")

        self.tree = ttk.Treeview(attr_frame,columns=tree_columns, show="headings",takefocus=False)
        self.tree.grid(column=0, row=0, sticky='nsew')

        for head in tree_columns:
            self.tree.heading(head,text=head,anchor="w")


root = tk.Tk()
myapp = Gui(root)
root.mainloop()

我還嘗試了幾種組合,包括;

style.configure('TScrollbar',background='blue') 

#and
style.configure('CustomScroll.Horizontal.TScrollbar',background='blue')

#in combination with
h_scroll = ttk.Scrollbar(scrl_attr_frame,orient="horizontal", command=attr_canvas.xview)
h_scroll['style'] = "CustomScroll.Horizontal.TScrollbar" 

非常感謝您的幫助!

看起來您只想更改Windows主題下水平滾動條的槽。 ttk小部件由樣式引擎提供的一組元素構成,並使用聲明的布局進行組合。 在Windows下,樣式引擎是Windows Visual Styles API,這意味着程序員無法控制用於繪制大多數常見元素的顏色或圖像。 按鈕背景,滾動條槽和按鈕以及拇指甚至滾動條拇指內繪制的手柄都由Windows提供。

可能采取的這種控制應用程序的定制,但在讓你的應用程序不再看給定的平台上標准的成本。 為此,您必須提供自己的UI元素並定義新的窗口小部件布局。 最終,這可以轉變為定義自己的主題。 ttk庫中的tcl腳本提供了很好的示例,甚至還有一些完整的(如果舊的)主題使用位圖來聲明原始版本的ttk中基於圖像的主題元素,這被稱為“tile”。

在這個具有自定義彩色背景的Windows水平滾動條的具體示例中,我們需要重新定義布局以使用Tk繪制元素中的滾動條槽。 “默認”主題中使用的元素可以復制並使用樣式配置參數定義,然后由Tk本身繪制,而不是傳遞給第三方引擎。 下面的代碼生成一個這樣的滾動條,它使用vsapi樣式引擎提供的標准按鈕和拇指,但替換了槽。 這個導入的槽了解troughcolor樣式配置選項,因此我們可以定義一個現在使用的顏色。 使用此樣式的所有滾動條將使用相同的顏色,因為窗口小部件本身將不接受troughcolor選項。 即:除非為每種新顏色定義新樣式,否則不能有一個滾動條為藍色而另一個滾動條為紅色。

在此輸入圖像描述

from tkinter import *
from tkinter.ttk import *

def main():
    app = Tk()
    style = Style()

    # import the 'trough' element from the 'default' engine.
    style.element_create("My.Horizontal.Scrollbar.trough", "from", "default")

    # Redefine the horizontal scrollbar layout to use the custom trough.
    # This one is appropriate for the 'vista' theme.
    style.layout("My.Horizontal.TScrollbar",
        [('My.Horizontal.Scrollbar.trough', {'children':
            [('Horizontal.Scrollbar.leftarrow', {'side': 'left', 'sticky': ''}),
             ('Horizontal.Scrollbar.rightarrow', {'side': 'right', 'sticky': ''}),
             ('Horizontal.Scrollbar.thumb', {'unit': '1', 'children':
                 [('Horizontal.Scrollbar.grip', {'sticky': ''})],
            'sticky': 'nswe'})],
        'sticky': 'we'})])
    # Copy original style configuration and add our new custom configuration option.
    style.configure("My.Horizontal.TScrollbar", *style.configure("Horizontal.TScrollbar"))
    style.configure("My.Horizontal.TScrollbar", troughcolor="red")

    # Create and show a widget using the custom style
    hs = Scrollbar(app, orient="horizontal", style="My.Horizontal.TScrollbar")
    hs.place(x=5, y=5, width=150)
    hs.set(0.2,0.3)

    app.mainloop()

if __name__ == '__main__':
    main()

如果你使用clam主題更容易:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
style = ttk.Style()
style.theme_use('clam')

# list the options of the style
# (Argument should be an element of TScrollbar, eg. "thumb", "trough", ...)
print(style.element_options("Horizontal.TScrollbar.thumb"))

# configure the style
style.configure("Horizontal.TScrollbar", gripcount=0,
                background="Green", darkcolor="DarkGreen", lightcolor="LightGreen",
                troughcolor="gray", bordercolor="blue", arrowcolor="white")

hs = ttk.Scrollbar(root, orient="horizontal")
hs.place(x=5, y=5, width=150)
hs.set(0.2,0.3)

root.mainloop()

這在Windows上的tkinter中似乎不可能。 下面的答案是這樣說的: ScrolledText Scrollbar Color(Python Tkinter)

滾動條文檔: http//infohost.nmt.edu/tcc/help/pubs/tkinter/web/scrollbar.html支持的樣式字段: http//infohost.nmt.edu/tcc/help/pubs/tkinter/web/ TTK-Scrollbar.html

我嘗試在我的Windows機器上傳遞'background'和'troughcolor'失敗。 我也嘗試將樣式應用於常規滾動條:style.configure('TScrollbar',background =“blue”)我的解決方案都沒有用。

另外一篇論壇帖子同意你不能在這里設置滾動條背景的樣式: http//www.gossamer-threads.com/lists/python/python/822292

這是一個獨立的解決方案 - 適用於水平和垂直滾動條。


def make_scrollbar_styles(
        troughcolor='black',
        background='grey',
        arrowcolor='white',
) -> Tuple[str, str]:
    """
    Style the scrollbars.  Usage:
        parent_frame = ... # tk.Frame(...) or tk.Tk() or whatever you're using for the parent
        hstyle, vstyle = make_scrollbar_styles()
        self._vbar = ttk.Scrollbar(parent_frame, orient='vertical', style=vstyle)
        self._hbar = ttk.Scrollbar(parent_frame, orient='horizontal', style=hstyle)
    """
    style = Style()

    for is_hori in (True, False):
        v = "Horizontal" if is_hori else "Vertical"
        style.element_create(f'CustomScrollbarStyle.{v}.Scrollbar.trough', 'from', 'default')
        style.element_create(f'CustomScrollbarStyle.{v}.Scrollbar.thumb', 'from', 'default')
        style.element_create(f'CustomScrollbarStyle.{v}.Scrollbar.leftarrow', 'from', 'default')
        style.element_create(f'CustomScrollbarStyle.{v}.Scrollbar.rightarrow', 'from', 'default')
        style.element_create(f'CustomScrollbarStyle.{v}.Scrollbar.grip', 'from', 'default')
        style.layout(
            f'CustomScrollbarStyle.{v}.TScrollbar',
            [(f'CustomScrollbarStyle.{v}.Scrollbar.trough', {
                'children': [
                    # Commenting in these 2 lines adds arrows (at least horizontally)
                    # (f'CustomScrollbarStyle.{v}.Scrollbar.leftarrow', {'side': 'left', 'sticky': ''}) if is_hori else (f'CustomScrollbarStyle.{v}.Scrollbar.uparrow', {'side': 'top', 'sticky': ''}),
                    # (f'CustomScrollbarStyle.{v}.Scrollbar.rightarrow', {'side': 'right', 'sticky': ''})  if is_hori else (f'CustomScrollbarStyle.{v}.Scrollbar.downarrow', {'side': 'bottom', 'sticky': ''}),
                    (f'CustomScrollbarStyle.{v}.Scrollbar.thumb', {
                        'unit': '1',
                        'children': [(f'CustomScrollbarStyle.{v}.Scrollbar.grip', {'sticky': ''})],
                        'sticky': 'nswe'}
                     )
                ],
                'sticky': 'we' if is_hori else 'ns'}),
             ])
        style.configure(f'CustomScrollbarStyle.{v}.TScrollbar', troughcolor=troughcolor, background=background, arrowcolor=arrowcolor)
        # Comment in the following to customize disable/active colors, whatever that means
        # style.map(f'CustomScrollbarStyle.{v}.TScrollbar', background=[('pressed', '!disabled', disabledcolor), ('active', 'orange')])
    return "CustomScrollbarStyle.Horizontal.TScrollbar", "CustomScrollbarStyle.Vertical.TScrollbar"

暫無
暫無

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

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