guizero/tkinter 如何将滑块转换为滚动条?

How do you convert a slider into a scrollbar in guizero/tkinter?

我正在尝试使用 Guizero 中与应用程序 window 和框小部件配合使用的滑块小部件制作滚动条。我想出了一种使用滑块移动对象的方法,但它不会动态变化。我需要一种滑块长度的方法,并根据不可见的项目数量限制它可以 scroll/move 向下移动的距离。我试过使用 tkinter 直接滚动条直接与 Guizero 但它只显示但不起作用。我需要使用 slider 因为它最容易添加到小部件。

我在用什么

我想做什么

我现在的代码

基于 Joe Michail 给出的答案 tkinter: binding mousewheel to scrollbar

from guizero import *
app=App(title='Guizero - Scrollbar slider',bg='blue',height=500,width=350)
def mouse_wheel(event):
    global count
    # respond to Linux or Windows wheel event
    if event.num == 4 or event.delta == -120:
        if count!=200:
            count += 2
    if event.num == 5 or event.delta == +120:
        if count>=0:
            count -= 2
    slider.value=count
    boxs.tk.place(x=0,y=-count)
count = 0

def slide():
    global count
    count=slider.value
    boxs.tk.place(x=0,y=-count)

# with Windows OS
app.tk.bind("<MouseWheel>", mouse_wheel)
# with Linux OS
app.tk.bind("<Button-4>", mouse_wheel)
app.tk.bind("<Button-5>", mouse_wheel)

#slider end need to change
slider = Slider(app,horizontal=False,width=8,height='fill',start=0, end=200,align='right',command=slide)
slider.tk.config(sliderrelief='flat',
                 sliderlength=(app.height/4),#need to change length dynamically
                 bd=1,
                 borderwidth=1,
                 highlightthickness=0,
                 showvalue=True,
                 fg='white',
                 troughcolor='white',
                 activebackground='orange',
                 bg='blue')

boxs=Box(app,align='right')

for x in range(1,12):    
    Hello_text=Text(boxs, text=" \nHello\n"+str(x), align="top")
    #change the look so you can tell them apart
    if x%2==1:
        Hello_text.bg='white'
    else:
        Hello_text.bg='lightblue'

#default box location
boxs.tk.place(x=0,y=0)

app.display()

每当 boxs 调整大小时,您都可以使用分配给 boxs.when_resized 的回调更新滑块范围:

def on_boxs_resized(event):
    slider.tk.config(to=event.tk_event.height-app.tk.winfo_height())

boxs.when_resized = on_boxs_resized

请注意,您可以在不使用全局变量的情况下简化 mouse_wheel()slide() 这两个函数 count:

def mouse_wheel(event):
    slider.value += 2 if event.delta < 0 else -2

def slide():
    boxs.tk.place(x=0, y=-slider.value)

已更新:您可以更新分配给 app.when_resized 的回调中的 sliderlength 选项:

def on_app_resized(event):
    percent = min(app.height/boxs.tk.winfo_height(), 1.0)
    sliderlength = slider.tk.winfo_height() * percent
    slider.tk.config(sliderlength=sliderlength)

app.when_resized = on_app_resized

# update the app
app.tk.update()
# adjust sliderlength of slider
on_app_resized(None)

app.display()