TypeError:unorderable类型:str()< INT()

时间:2015-09-15 16:12:56

标签: python tkinter

需要有关此错误的帮助。

我的代码:

from tkinter import *

def shouldIEat():

    if calories.get() < 1523 :
     answer.set("Eat food as soon as possible")

    elif calories.get() > 1828 :
     answer.set("Stop eating")

    else:
     answer.set("You can eat something, but don't go over 1828")

window = Tk()

answer = StringVar()
calories = IntVar()



calories.set(0)


caloriesLabel = Label(window, text = "How many calories have you consumed?")
caloriesLabel.grid( row = 1)

calories = Entry(width = 10)
calories.grid (row = 1, column = 1)

eatButton = Button(window, text = "Should I eat?" , command=shouldIEat).grid( row = 2 , column = 1)
quitButton = Button(window, text = "Quit" ,  command=window.quit).grid( row = 2 , column = 2)

window.mainloop()

我的错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
    return self.func(*args)
  File "D:/My Documents/School/Scripting Lang/Project", line 8, in shouldIEat
    if calories.get() < 1523 :
TypeError: unorderable types: str() < int()

2 个答案:

答案 0 :(得分:2)

您的代码将calories设置为Tkinter IntVar,但随后它通过创建具有相同名称的条目来破坏它。您需要为Entry指定一个不同的名称,然后使用Entry构造函数中的calories参数附加textvariable IntVar。

此外,您从未创建过小部件来显示答案。

from tkinter import *

def shouldIEat():
    if calories.get() < 1523 :
        answer.set("Eat food as soon as possible")
    elif calories.get() > 1828 :
        answer.set("Stop eating")
    else:
        answer.set("You can eat something, but don't go over 1828")

window = Tk()

answer = StringVar()
calories = IntVar()

calories.set(0)
#answer.set('')

caloriesLabel = Label(window, text = "How many calories have you consumed?")
caloriesLabel.grid(row = 1, column = 0)

caloriesEntry = Entry(width = 10, textvariable=calories)
caloriesEntry.grid(row = 1, column = 1)

Button(window, text = "Should I eat?", command=shouldIEat).grid(row = 2, column = 1)
Button(window, text = "Quit" , command=window.quit).grid(row = 2, column = 2)

answerLabel = Label(window, textvariable=answer)
answerLabel.grid(row = 2, column = 0)

window.mainloop()

我们并不需要初始化answer,但这样做更为全面。如果你愿意,你可以用它来显示一些简单的指令。

我应该提及您的代码的另一个小问题。

eatButton = Button(window, text = "Should I eat?" , command=shouldIEat).grid( row = 2 , column = 1)

这将创建一个Button对象,然后调用其.grid()方法。没问题,但.grid()方法返回None返回Button对象,因此将返回值保存到{{1没有意义。您不需要为此程序保留对该按钮的引用,这就是我将其更改为

的原因
eatButton

在我的版本中。但是当你需要保持对小部件的引用时,你应该在一行上构建它,然后在单独的行上应用Button(window, text = "Should I eat?", command=shouldIEat).grid(row = 2, column = 1) (或.grid())方法,如你使用.pack()


BTW,在Python中,caloriesLabel形式的名称优先于calories_label。有关详细信息,请参阅PEP-008

答案 1 :(得分:0)

正如您在TypeError中看到的那样,您正在将字符串与整数进行比较。

在进行比较之前将字符串转换为整数。