Several Tk widgets also exist in Ttk versions. Usually they have the same general behaviour, but use "styles" and "themes" rather than per-instance appearance attributes (such as bg
, etc...). This is good, as the Ttk widgets take the "standard appearance" of the OS's window manager by default, without needing to configure anything about appearance.
However, for some reason the ttk.Scale
widget does not have two very useful options of the tk.Scale
widget: showvalue
and tickinterval
(see reference). This is strange as those are more about behaviour than about look.
It would be great to "immitate" these two options while keeping a ttk
look.
The following code is my clumsy attempt at this. The question is: is there a better way? (besides encapsulating the whole thing in a class, obviously) and how would one reasonably get a semi-automated tickinterval
substitute (rather than doing it "by hand" as in the code below).
import tkinter as tk
import tkinter.ttk as ttk
# initial setup
root = tk.Tk()
frame = tk.Frame(root)
#################################################################
# create a tk slider showing current value and ticks
# (showvalue=True is the default)
tkslider = tk.Scale(frame, from_=-4, to=4,
orient=tk.HORIZONTAL, tickinterval=2)
#################################################################
#################################################################
# create a ttk slider showing current value and ticks
# use a ttk frame to get ttk style background
ttkslider = ttk.Frame(frame)
# define a callback function to update the value label
def ttk_slider_callback(value):
# 'value' seems to be a string - bug or feature?
value_label.config(text=round(float(value)))
# 'text' can apparently be an int and gets converted into str
# (...) possibly do other stuff
# decompose frame into two ttk labels and a ttk scale
value_label = ttk.Label(ttkslider, text=0)
actual_slider = ttk.Scale(ttkslider, from_=-4, to=4,
command=ttk_slider_callback)
# (orient=tk.HORIZONTAL is the default)
ticks_label = ttk.Label(ttkslider, text=' -4 -2 0 2 4 ')
# put it all together
value_label.grid()
actual_slider.grid()
ticks_label.grid()
#################################################################
# final setup
tkslider.grid(row=0, column=0)
ttkslider.grid(row=0, column=1)
frame.grid()
root.mainloop()
The result of the previous code, before actualy "sliding" the Scales, may look like this, with the Tk Scale on the left and the Ttk Scale on the right (will vary obviously per OS / window manager):