tkinter中动态调整浮点spinbox增量

2024-10-04 05:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望能够动态调整下面的浮点数字微调框(spin1)的增量。为此,我创建了第二个自旋框(spin2),它的值(0.1, 0.01, 0.001, 0.0001),决定了spin1的步长

只要我总是从较粗的增量移动到较细的增量,这就可以很好地工作。当我尝试从更细的增量移动到更粗的增量时,它失败了,因为该值被截断到增量的精度

使用以下代码,可以重现问题:

  1. spin1移动到0.2

    enter image description here

  2. 增量spin2,比如说0.01

    enter image description here

  3. spin1增加到0.21

    enter image description here

  4. 减量spin2回到0.1

    enter image description here

  5. 减量spin1

    enter image description here

我希望在spin1中看到值0.11,但我看到的是0.1。为什么会发生这种情况,我如何修复它

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()

补充意见:

  • 微调器始终截断值,而不是舍入值。因此,如果在步骤3中将spin1设置为2.6,最终结果仍然是0.1,而不是0.2

Tags: from动态update数字window增量packtk