Home > Software engineering >  I get TypeError: '>' not supported between instances of 'float'
I get TypeError: '>' not supported between instances of 'float'

Time:03-10

I would like to get the "Ok" print of a number (B = 2 2) if > to number that I insert in a textbox.

The first number is

A = 2   2

A = Entry (root, width = 4, highlightthickness = 0, bg = "# ffffc0")
A.place (x = 1, y = 1)

if B > A:
     print ("Ok")

I get TypeError: '>' not supported between instances of 'float'

How can I solve?

CodePudding user response:

The call to Entry() returns an object which is a text widget and is stored in number2. To get its contents, you need to call its get() method. The result will be of type str.

You will need to call int(number2.get()) or float(number2.get()) to get a variable whose type is compatible with that of the variable number1 shown in your question.

CodePudding user response:

You cannot compare an Entry widget with a float variable. Refer to the documentation, to know more.

So store the data (textvariable) of Entry widget in a StringVar variable (For double values, you can use DoubleVar also in Tkinter), then while comparing typecast it to float or int, depending on what kind of number input is.

So, considering the number getting as input in the Entry box and the number1 are both integer values (can be large integers too, with commas.) I will store the numbers as strings. (If the values are decimals, use float instead of int.)

In order to compare the numbers stored in strings, I'll be creating a function valueOf to get the values of those strings as int with commas removed.

This snippet will give you an idea:

from tkinter import *
window = Tk()

number2 = StringVar() #take the input number2 as a string (so that commas are also included)
entry_1 = Entry(window,textvariable=number2) #assign number2 as textvariable of this Entry box.
entry_1.place(x = 1, y = 1)

def valueOf(s):
    if type(s) == str :
        s = s.replace(',', '')          #removes the commas from the number
        if s=="" :                      #in case nothing was given in Entry box, consider it as 0
            return 0
    return int(s)                       #return the integer form of that number
    
def Compare():
    #number1 = "2,552,555"              #make sure to take this number as a string if commas are there
    number1= 2 2                        #this is already in int form
    if valueOf(number1) > valueOf(number2.get()):
         print ("Ok")
    else:
         print("Input is Equal or Greater")

button1 = Button(window, text="Print", command=Compare)
button1.place(x = 45, y = 30)
window.mainloop()
  • Related