Search code examples
pythontkinterttktkinter-scale

Unknow option for tkinter scale widget


I am coding a GUI where you have to enter a number. I want to have a scale but it fits my purpose very well. The problem is a scale goes to 1e-9 precision. This is much to precise for me. I am using ttk extension for tkinter. I have tried a couple of things but I saw that there is a digits option for the scale which, when there is a StringVar(), leaves the number of digits but it doesn't work, it cannot recognise the option. I tried to look in the library but I couldn't find anything, it was too complicated.

Here is how my code is formed:

scaleValue = StringVar()
scale = ttk.Scale(content, orient=HORIZONTAL, from_=1, to=5, variable=scaleValue, length=150, digits=1)  # here digits ins't recongnised
scale.grid(column=x, row=y)

scaleValueLabel = ttk.Label(content, textvariable=scaleValue)
scaleValueLabel.grid(column=x', row=y')

Here is the documentation:

An integer specifying how many significant digits should be retained when converting the value of the scale to a string. Official Documentation : http://www.tcl.tk/man/tcl8.6/TkCmd/scale.htm


Solution

  • digits is a parameter only available to tk.Scale. If you switch to using it, then your code will work:

    scale = tk.Scale(root, orient=tk.HORIZONTAL, from_=1, to=5, variable=scaleValue, length=150, digits=5)
    

    But if you really want to use ttk.Scale, you can use a different approach. Instead of using a textvariable in your Label, you can trace the changes on your variable, process the value first, and then pass back to your Label.

    import tkinter as tk
    from tkinter import ttk
    
    root = tk.Tk()
    
    scaleValue = tk.DoubleVar()
    scale = ttk.Scale(root, orient=tk.HORIZONTAL, from_=1, to=5, variable=scaleValue, length=150)  # here digits ins't recongnised
    scale.grid(column=0, row=0)
    
    scaleValueLabel = tk.Label(root, text="0")
    scaleValueLabel.grid(column=0, row=1)
    
    def set_digit(*args):
        scaleValueLabel.config(text="{0:.2f}".format(scaleValue.get()))
    
    scaleValue.trace("w", set_digit)
    
    root.mainloop()