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:
Move
spin1
to0.2
:Increment
spin2
, say to0.01
:Increment
spin1
to0.21
:Decrement
spin2
back to0.1
:Decrement
spin1
:
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 to2.6
in step 3, the final result would still be0.1
, not0.2
.