How to use tkinter slider `Scale` widget with discrete steps?

后端 未结 1 1460
慢半拍i
慢半拍i 2021-01-18 18:29

Is it possible to have a slider (Scale widget in tkinter) where the possible values that are displayed when manipulating the slider are discrete values read fro

相关标签:
1条回答
  • 2021-01-18 19:02

    Edit you could set the command of the slider to a callback, have that callback compare the current value to your list and then jump to the nearest by calling set() on the slider

    so:

    slider = Slider(parent, from_=0, to=100000, command=callback)
    

    and:

    def callback(event):
        current = event.widget.get()
        #compare value here and select nearest
        event.widget.set(newvalue)
    

    Edit: to show a complete (but simple example)

    try:
        import tkinter as tk
    except ImportError:
        import Tkinter as tk
    
    valuelist = [0,10,30,60,100,150,210,270]
    
    def valuecheck(value):
        newvalue = min(valuelist, key=lambda x:abs(x-float(value)))
        slider.set(newvalue)
    
    root = tk.Tk()
    
    slider = tk.Scale(root, from_=min(valuelist), to=max(valuelist), command=valuecheck, orient="horizontal")
    
    slider.pack()
    
    root.mainloop()
    

    i've tested this in python 2.7.6 and 3.3.2, even when dragging the slider this jumps to the nearest value to where the mouse is currently as opposed to only jumping when you let go of the slider.

    0 讨论(0)
提交回复
热议问题