python if条件不能按预期正常工作

2024-04-25 09:04:30 发布

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

在onClick\u按钮事件中,我有一个if条件,在条件失败时显示messagedialog,否则执行其余语句。 基本上,如果条件是检查textctrl是否有值。如果有值,则执行else语句。你知道吗

这是第一次使用msgdlg在tc(textctrls)中没有任何值的情况下工作,但是当单击dlg上的ok并在tc中添加一些值时,msgdlg仍然会在应该执行else时弹出。你知道吗

非常感谢你的帮助。 我检查了所有的压痕。你知道吗

def onClick_button_new(self, event):

    self.list_box.Clear()
    varstr = "csv"


    if [(self.tc1.GetValue() == "") or (self.tc2.GetValue() == "")]:
        dial = wx.MessageDialog(None, 'No file specified.  Please specify relevant file', 'Error', wx.OK)
        dial.ShowModal()
    else:
        file1 = subprocess.check_output("cut -d '.' -f2 <<< %s" %self.var1, shell = True, executable="bash")
        file1type = file1.strip()
        print file1type
        file2 = subprocess.check_output("cut -d '.' -f2 <<< %s" %self.var2, shell = True, executable="bash")
        file2type = file2.strip()
        if varstr in (file1type, file2type):
            print "yes"
        else:
            dial = wx.MessageDialog(None, ' Invalid file format.  Please specify relevant file', 'Error', wx.OK)
            dial.ShowModal()

Tags: selfif语句条件elsefiletcwx
3条回答

取决于你的意见

[(self.tc1.GetValue() == "") or (self.tc2.GetValue() == "")]

[True][False]。在任何情况下都是非空列表。这将被解释为True

if [False]:
    do_something()

在本例中,将始终执行do_something()。你知道吗

要解决这个问题,您需要删除括号[]

if (self.tc1.GetValue() == "") or (self.tc2.GetValue() == ""):
    ...

不需要将方法结果与空字符串进行比较:

if not self.tc1.GetValue() and not self.tc2.GetValue():

看那篇文章:Most elegant way to check if the string is empty in Python?

您将布尔逻辑混合在一起,并创建了一个list对象(该对象总是非空且总是真)。要使用and而不是使用列表:

if self.tc1.GetValue() == "" and self.tc2.GetValue() == "":

千万不要将[...]列表用于布尔测试,因为这只会创建一个不为空的列表对象,因此在布尔上下文中始终被视为true,而不管包含的比较结果如何:

>>> [0 == 1 or 0 == 1]
[False]
>>> bool([0 == 1 or 0 == 1])
True

相关问题 更多 >

    热门问题