我的代码遇到了一些问题.. 如果值不在 0-255 之间,我希望我的代码弹出一个消息框,但它不起作用。我现在只是使用 c>255 进行故障排除,但我不知道问题出在哪里。即使它的 if c>255,当值低于 255 时它仍然显示消息框。有人能告诉我我做错了什么吗:\
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"
请您参考如下方法:
self.c 不是数字而是字符串,字符串总是大于任何数字(参见 here for an explanation about this comparison )。
尝试在比较之前将 self.c 转换为 int :
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()
在 Python3 中,这种不同类型的比较会引发 TypeError。
