1

I'm experiencing some problems with my code.. I want my code to popup a messagebox if the value is not in between 0-255, but it's not working. I'm just using c>255 to troubleshoot right now but I don't know what the problem seems to be. Even though its if c>255, it still displays the messagebox when the value is under 255. Can someone tell me what I'm doing wrong :\

  def clicked_wbbalance(self):
    self.top = Toplevel()
    self.top.title("LASKJDF...")
    Label(self.top, text="Enter low level").grid(row=0, column=0,padx=10)
    Label(self.top, text="Enter high level").grid(row=1, column=0,padx=10)
    Label(self.top, text="Values must be between 0 to 255").grid(row=3, column=0)


    self.a = Entry(self.top)
    self.b = Entry(self.top)
    self.a.grid(row=0, column=1,padx=10)
    self.b.grid(row=1, column=1,padx=10)
    Button(self.top, text="Ok", command=self.get).grid(row=3, column = 1)



def get(self):
    self.c = self.a.get()
    self.d = self.b.get()
    if self.c > 255:
        tkMessageBox.showerror("Error", "Please enter a value between 0-255")
        self.clicked_wbbalance()
    else:
        print "asdfasd"
user1730056
  • 623
  • 3
  • 11
  • 19

1 Answers1

8

self.c is not a number but a string, and a string will always be greater than any number (cf here for an explanation about this comparison).

Try to transform self.c into an int before comparison :

try:
    c_as_int = int(self.c)
except ValueError:
    tkMessageBox.showerror("Error", "Please enter a value between 0-255")
    self.clicked_wbbalance()
else:
    if c_as_int > 255:
        tkMessageBox.showerror("Error", "Please enter a value between 0-255")

        self.clicked_wbbalance()

In Python3 this kind of different type comparison will raise a TypeError.

Community
  • 1
  • 1
Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
  • yup that was the problem, it was a string :) thanks a lot! I got it solved – user1730056 Nov 12 '12 at 08:57
  • Hi, I have another question. I would like to display ` tkMessageBox.showerror("Error2", "Please enter a value between 0-255")` if the value entered is not an int. Is there a way to do this? – user1730056 Nov 12 '12 at 09:08
  • 1
    You will get a `ValueError` from `int()` if the value is not an integer representation. So just use a try/except block when converting the string to an integer. – James Henstridge Nov 12 '12 at 09:16
  • @user1730056 : as mentionned by JamesHenstridge I added the try/except ValueError statement. – Cédric Julien Nov 12 '12 at 10:35