python3.x IF语句,以便在tk上填充多个输入字段时生成结果

2024-09-24 22:27:26 发布

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

我有4个输入字段,我想弹出一个错误消息时,这些领域有一个以上的条目。听起来很简单,但我似乎无法得到一个if语句来做我想做的事情。你知道吗

我当前的非工作代码是此处:-你知道吗

        val1 = (entry1.get())
        val2 = (entry2.get())
        rval1 = (rootentry1.get())
        rval2 = (rootentry2.get())
        rval3 = (rootentry3.get())
        rval4 = (rootentry4.get())
        glthickval = (glthick.get())
        glthickvalfloat = float(glthickval)
        validation = 0
        global data

        try:
            int(val1)
            int(val2)
        except ValueError:
            message5 = 'The number must be a whole number!'
            box.showerror("Invalid Input", message5)

        if int(rval1+rval2+rval3+rval4) > 0:
            if int(rval1) and int(rval2) and int(rval3) and int(rval4) >0:
                message7 = 'You have selected more than one type of root!'
                box.showerror("Invalid Input",message7)

这个底部部分是我无法工作的部分,很明显,只有当所有值都大于0时,规则才会标记。也许还有别的办法?你知道吗

提前谢谢。你知道吗


Tags: andboxnumbergetifintval1val2
3条回答

我想你可以用这个

if len(list(filter(lambda x: x is not None, [rval1, rval2, rval3, rval4]))) > 1:
  # you've got more than one value that's not none

在这里有很多答案,有很好的列表理解,和lambda的,和其他聪明的东西,但他们似乎都减损了你想做的可读性。。。你知道吗

我会做一个小函数,告诉你有多少条目被填充,比如:

def filledEntries(entries):
  filledEntryCount = 0
  for entry in entries:
    if entry != 0: filledEntryCount += 1

  return filledEntryCount

然后就有了

if filledEntries(entries) > 1:
  box.showerror("Invalid Input", "You have selected more than one type of root!")

列出所有值,筛选出等于零的值,然后测量结果的长度。你知道吗

values = [rval1, rval2, rval3, rval4]
filled_values = [value for value in values if int(value) != 0]
if len(filled_values) > 1:
    print "You have selected more than one type of root!"

顺便说一句,当你有多个变量的名字只有一个数字不同的结尾,这通常是一个很好的迹象,你应该使用一个列表。考虑使用一个root_entries列表,其中包含四个根条目对象。你知道吗

相关问题 更多 >