0

我正在使用 Python 中的 Tkinter,但我对Scale小部件有疑问。我想做的是对Scale的某些值采取行动。

这是Scale代码的一部分:

self.scale = Scale(from_=0, to=100, tickinterval=20, orient=HORIZONTAL, command= self.scale_onChange)

def scale_onChange(self, value):
    if(value >= 10):
        print "The value is ten"

发生了一些奇怪的事情,当我运行脚本时,比例值为 0,但条件似乎为真并打印“值为 10”。此外,当我更改刻度的值时,即使值大于 10,它也不会匹配条件。

4

1 回答 1

1

你有一个类型不匹配。value是字符串而不是数字类型,并且在 Python 2.*'0'中大于10. 感谢 Tadhg McDonald-Jensen 指出这种静默错误是 Python 2.* 特有的。

from Tkinter import *

def scale_onChange(value):
    print(value)
    print(type(value))
    if(value >= 10):
        print "The value is ten"

master = Tk()
scale = Scale(from_=0, to=100, tickinterval=20, orient=HORIZONTAL, command=scale_onChange)
scale.pack()

mainloop()

例如

>>> '0' >= 10
True

在 Python 3.* 中你会得到一个错误:

>>> '0' >= 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() >= int()
于 2016-10-25T16:34:59.403 回答