Skip to content
Advertisement

Create automatic tick labels for a tkinter scale

I want to create a scale with tick labels that are automatically chosen so they fit on to the scale without interfering with each other.

Here is an example code for crating one that resizes with the window:

from tkinter import *

window = Tk()

scale = Scale(from_=1, to=1000, orient=HORIZONTAL)
scale.pack(fill=X)

window.mainloop()

When creating a plot with matplotlib, this happens by default and even gets updated when changing the size of the plot window.

Is there a way to accomplish the same for a tkinter scale widget? The result should look something like this:

scale example image

Advertisement

Answer

For that, there is an option called tickinterval.

From a doc:

Normally, no “ticks” are displayed along the scale. To display periodic scale values, set this option to a number, and ticks will be displayed on multiples of that value. For example, if from_=0.0, to=1.0, and tickinterval=0.25, labels will be displayed along the scale at values 0.0, 0.25, 0.50, 0.75, and 1.00. These labels appear below the scale if horizontal, to its left if vertical. Default is 0, which suppresses display of ticks.

So:

from tkinter import * # Better to use `import tkinter as tk`

root = Tk()

var  = StringVar()
Label(root,textvariable=var).pack()

Scale(root,from_=1, to=25, orient=HORIZONTAL, tickinterval=1, showvalue=0, variable=var, length=1000).pack(fill=X)

root.mainloop()

Output: ss

For more info, read: 21. The Scale widget


However what you are asking is for an automatic calculation algorithm with which tkinter would resize and fit in the length to the scale, sadly it is not available AFAIK and this is the closest method I can think of.

Advertisement