-2

I want to be able to dynamically adjust the increment for my floating point numerical spinbox (spin1) below. To do so, I've created a second spin box (spin2) that has values (0.1, 0.01, 0.001, 0.0001), which determine the step size of spin1.

This works fine as long as I always move from coarser to finer increments. It fails when I attempt to move from a finer to a coarser increment because the value gets truncated to the precision of the increment.

Using the code below, here is how the problem can be reproduced:

  1. Move spin1 to 0.2:

    enter image description here

  2. Increment spin2, say to 0.01:

    enter image description here

  3. Increment spin1 to 0.21:

    enter image description here

  4. Decrement spin2 back to 0.1:

    enter image description here

  5. Decrement spin1:

    enter image description here

I would expect to see the value 0.11 in spin1, but instead I see 0.1. Why is this happening, and how can I fix it?

from tkinter import Tk, Spinbox

def update():
    spin1['increment'] = float(spin2.get())

window = Tk()
spin1 = Spinbox(window, from_=0.0, to=10.0, increment=0.1)
spin2 = Spinbox(window, values=(0.1, 0.01, 0.001, 0.0001), command=update)
spin1.pack()
spin2.pack()
window.mainloop()

Additional observation:

  • The spinner always truncates values rather than rounding. So if spin1 were set to 2.6 in step 3, the final result would still be 0.1, not 0.2.
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

1 Answers1

1

You can add format="%.4f" (based on the maximum decimal points of 0.0001 from spin2) to spin1:

spin1 = Spinbox(window, from_=0.0, to=10.0, increment=0.1, format="%.4f")
acw1668
  • 40,144
  • 5
  • 22
  • 34