【问题标题】:How to do an action for certain values of tkinter Scale widget?如何对 tkinter Scale 小部件的某些值执行操作?
【发布时间】:2016-10-25 16:23:02
【问题描述】:

我正在使用 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,也不会匹配条件。

【问题讨论】:

    标签: python python-2.7 tkinter tkinter-scale


    【解决方案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()
    

    【讨论】:

    • 谢谢,我没想到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多