Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

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

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 from a list?

The values in my list are not in even steps and are situation dependent.

From all the examples I've seen, you can specify a minimum value, a maximum value and a step value (n values at a time), but my list might look like this:

list=['0', '2000', '6400', '9200', '12100', '15060', '15080']

Just as an example. To reiterate, I want it go from for instance list[0] to list[1] or list[6] to list[5] when pulling the slider.

If anyone has any other suggestion for easily being able to pick a value from hundreds of items in a list, I'm all ears. I tried the OptionMenu widget but it gets to extensive and hard get a view of.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...