使用 ttk 樣式更改 Tkinter 中捲軸的外觀


捲軸用於將一定數量的文字或字元包裹在框架或視窗中。它提供了一個文字小元件來容納使用者想要的任意數量的字元。

捲軸可以分為兩種型別:水平捲軸和垂直捲軸。

文字小元件中字元數發生變化時,捲軸的長度也會隨之變化。我們可以使用 ttk.Scrollbar來配置捲軸的樣式。Ttk 提供了許多內建功能和屬性,可用於配置捲軸。

示例

在此示例中,我們將在一個文字小元件中新增一個垂直捲軸。我們將使用 ttk 樣式主題來定製捲軸的外觀。這裡我們使用了“經典”主題。有關 ttk 主題的完整列表,請參考此連結

# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of Tkinter Frame
win = Tk()

# Set the geometry of Tkinter Frame
win.geometry("700x250")

style=ttk.Style()
style.theme_use('classic')
style.configure("Vertical.TScrollbar", background="green", bordercolor="red", arrowcolor="white")

# Create a vertical scrollbar
scrollbar = ttk.Scrollbar(win, orient='vertical')
scrollbar.pack(side=RIGHT, fill=BOTH)

# Add a Text Widget
text = Text(win, width=15, height=15, wrap=CHAR,
yscrollcommand=scrollbar.set)

for i in range(1000):
   text.insert(END, i)

text.pack(side=TOP, fill=X)

# Configure the scrollbar
scrollbar.config(command=text.yview)

win.mainloop()

輸出

執行上面的程式碼將顯示一個帶有文字小元件和自定義垂直捲軸的視窗。

更新於: 2021 年 5 月 25 日

檢視量 4000+

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.