If 语句有效 elif 语句被跳过,else 语句在 python 中有效

问题描述 投票:0回答:1

我已经浏览了有关堆栈溢出的所有其他“它正在跳过我的 elif 语句”帖子,但它们并不适用。我对 python 和 tkinter 很陌生,所以它可能是一些基本的东西。 我正在尝试使用选定的框架在 tkinter 中打开一个新窗口。 可能有一种更简单的方法来做到这一点,但我将选择写入文本文件,然后这部分读取文本并根据它的内容打开窗口到正确的框架。

问题是它将打开 if 语句框架,但否则它将打开 else 语句框架。没有给出错误。我可以改变顺序,所有框架都可以工作,但只能在 if 或 else 位置。 elifs 不起作用。 我认为它需要处于 while 循环中,但每次我尝试它都会崩溃

提前致谢!

 with open("select.txt", "r") as file:
       
        if "Foo" in file:
            foo_page()
        elif "Bar" in file:
            bar_page()
        elif "Doo" in file:
            doo_page()
        elif "Baa" in file:
            baa_page()
        elif "Doop" in file:
            doop_page()
        elif "Ahh" in file:
            ahh_page()
        elif "Dee" in file:
            dee_page()
        elif "Dum" in file:
            dum_page()
        else:
            oompa_page()

    win2.mainloop()
python if-statement tkinter
1个回答
0
投票
  • 在您的代码中,当您打开文件时,
    file
    它是缓冲原始流(BufferedIOBase)的缓冲文本接口,您不能像那样设置条件。
  • 您需要将文件的内容读入变量,然后对该变量执行检查。
with open("select.txt", "r") as file:
    file_contents = file.read()

if "Foo" in file_contents:
    foo_page()
elif "Bar" in file_contents:
    bar_page()
elif "Doo" in file_contents:
    doo_page()

# Rest of the Code
© www.soinside.com 2019 - 2024. All rights reserved.