Python Tkin上的Buggy“if c>255”语句

2024-10-01 22:36:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码遇到了一些问题。。 如果值不在0-255之间,但不起作用,我希望代码弹出一个messagebox。我现在只是用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"

Tags: 代码textgtselfgetiftopdef
1条回答
网友
1楼 · 发布于 2024-10-01 22:36:26

self.c不是一个数字而是一个字符串,字符串总是大于任何数字(cfhere 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")

你知道吗自平衡()

在Python3中,这种不同类型的比较会引起TypeError。你知道吗

相关问题 更多 >

    热门问题