Tkinter (17) 滚动条部件 Scrollbar

滚动条部件的创建及其选项

滚动条部件中包含滑块slider, 前后两个箭头arrow1, arrow2, 滑块槽trough (分前后两头滑块槽trough1/trough2), 滑块的大小及位置代表可见的部份占全部内容的比例及位置 (0.0 ~ 1.0).

import tkinter as tk
root = tk.Tk()
parent_widget = ...
scroll_bar = tk.Scrollbar(parent_widget, option, ...)
选项 说明
activebackground active 时的背景色
activerelief active 时的滑块花边样式,内定为 RAISED
bg or background 背景色,非 active 时滑块及箭头的颜色
bd or borderwidth 滑块槽框, 滑块及箭头框的寛度,内定滑块槽无框, 滑块及箭头框的寛度为 2 点素
command 滑块位置改变时调用的程序
cursor 当鼠标移到部件时,所显示的鼠标图示
elementborderwidth 滑块及箭头框的寛度, 内定为 -1, 使用 bd or borderwidth 的值
highlightbackground 非聚焦时的聚焦颜色
highlightcolor 聚焦时的聚焦颜色
highlightthickness 聚焦厚度,内定 1, 0 则无
jump 是否立刻调用 command, 内定为 0, 每一小步都调用, 1 则直到释到鼠标按键才调用
orient 水平或垂直滚动​​条, HORIZONTAL/VERTICAL
relief 花边样式,内定为 SUNKEN
repeatdelay 直到经过指定时间 (毫秒), 开始重复按下滑块槽,内定 300ms
repeatinterval 重复间隔,以毫秒为单位重复按下滑块槽,内定 100ms
takefocus TAB 键在部件是否会循环焦点,1 则会,内定为空字符串,则仅在具有键绑定下循环焦点
troughcolor 滑块槽的颜色
width 滚动条部件寛度,内定为 16 点素

滚动条部件的方法

方法 说明
activate(element=None) 返回鼠标所在零件, ‘slider’/‘arrow1’/‘arrow2’/‘’ (其他), 或者设置聚焦在该零件
delta(dx, dy) 如同鼠标移动 (dx, dy), 返回目前滑块相对移动量, 该值在 -1.0 ~ +1.0
fraction(x, y) 返回相对于 (x, y) 位置的滑块位置, 0.0 ~ +1.0
get() 返回目前滑块位置的前缘 a 与后缘 b, (a, b), 0.0 ~ +1.0
identify(x, y) 返回 (x, y) 所在的零件, ‘slider’/‘arrow1’/‘arrow2’/‘trough1’/‘trough12’/‘’ (其他)
set(first, last) 要带有滚动条的主部件, 其 xscrollcommnad/yscrollcommand 设为本方法, 本方法的参数同get方法返回的结果同意义

注: 移动滚动条并不会移动滚动其主部件.

滚动条部件的回调

  • command(tk.SCROLL, -1, tk.UINTS) 滚动条前移一小单位
  • command(tk.SCROLL, 1, tk.UINTS) 滚动条后移一小单位
  • command(tk.SCROLL, -1, tk.PAGES) 滚动条前移一小页面
  • command(tk.SCROLL, 1, tk.PAGES) 滚动条后移一小页面
  • command(tk.MOVETO, f) 滚动条移到相对位置 f: 0.0 ~ +1.0

设置主部件与滚动条部件的连结

  • 主部件的 xscrollcommand/yscrollcommand 为滚动条部件的 set 方法
  • 水平/垂直滚动条部件的 command 为主部件的 xview/yview 方法
  • 水平/垂直滚动条部件的 grid 方法选项 sticky, 应该要设置为 EW/NS.

范例视窗及代码

Python

import tkinter as tk

root = tk.Tk()
root.wm_title("Scrollbar Demo")

font = ('Courier New', 16, 'bold')

elements = ('List for House', 'List for Friend', 'List for Cash', 'List for Car',
            'List for Motorcycle', 'List for Boat', 'List for Airplane')

x_scrollbar = tk.Scrollbar(root, orient=tk.HORIZONTAL)
x_scrollbar.grid(row=1, column=0, sticky=tk.E+tk.W)
y_scrollbar = tk.Scrollbar(root, orient=tk.VERTICAL)
y_scrollbar.grid(row=0, column=1, sticky=tk.N+tk.S)

list_box = tk.Listbox(root, font=font, selectmode=tk.MULTIPLE,
    width=15, height=5, activestyle='dotbox', xscrollcommand=x_scrollbar.set,
    yscrollcommand=y_scrollbar.set)
list_box.insert(tk.END, *elements)
list_box.grid(row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W)

x_scrollbar['command'] = list_box.xview
y_scrollbar['command'] = list_box.yview

root.mainloop()
本作品采用《CC 协议》,转载必须注明作者和本文链接
Jason Yang
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!