Search code examples
pythonif-statementtkinter

If Statement works elif statements skipped, else statement works in python


I have looked through all of the other "it is skipping my elif statements" posts on stack overflow and they do not apply. I am new to python and tkinter so it is probably something basic. I am trying to open a new window in tkinter with a chosen frame. there may be an easier way to do this but i have the selection written in a text file then this part reads the text and according to what it says, opens the window to the correct frame.

the problem is it will open the if statement frame but otherwise it will open the else statement frame. There is no error given. i can change the order around and all the frames work, but only in the if or else position. the elifs will not work. I'm thinking it needs to be in a while loop but everytime I've tried it crashes

thanks in advance!

 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()

Solution

    • In your Code, when you open the file, file object is buffered text interface to a buffered raw stream ( BufferedIOBase), You cannot put conditions on like that.
    • You need to read the contents of the file into a variable and then perform your checks on that variable.
    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