Вопрос

I'm writing a small program that's supposed to find the longest sentence in a text file. I keep reading my code but I don't get why it's not working. The program is using an Entry widget. Basically the search() function handles a few exceptions (this part is working) and if you enter a valid file name, it jumps over to the while loop. The while loop reads every line and assigns the longest to longest. As soon as it reaches an empty line, the elif statement is executed (or should be). It's supposed to display the longest sentence in the Entry widget. The problem is nothings shows up in the entry widget in the end.

I'm using Python 3 on Windows.

Here is my code:

from tkinter import *

def search(event):
    try:
        txtFile = open(str(entr.get()), 'r')
    except:
        entr.delete(0, END)
        entr.insert(0, "File can't be found")
    else:
        x = 0
        while 1:
            rd = txtFile.readline()
            if len(rd)> x:
                longest = rd
                x = len(rd)
            elif rd == '':
                break
                txtFile.close()
                entr.delete(0, END)
                entr.insert(0, longest)

#####MAIN#####

wd = Tk()
wd.title('Longest sentence searcher')
entr = Entry(wd, bg='White')
entr.grid(row=0, column=0)
entr.bind('<Return>', search)
bttn = Button(wd, text='Search', bg='Light Green')
bttn.grid(row=1, column =0)
bttn.bind('<Button-1>', search)

wd.mainloop()
Это было полезно?

Решение

The problem is that your code for closing the file and displaying the longest line is never executed:

    while 1:
        rd = txtFile.readline()
        if len(rd)> x:
            longest = rd
            x = len(rd)
        elif rd == '':
            break
            txtFile.close()
            entr.delete(0, END)
            entr.insert(0, longest)

break breaks out of the while-loop, and as there is no more code after it, Python returns from the function. Move the last three lines out of the while-loop and you should be good:

    # Using 'True' for infinite loops is more idiomatic/pythonic
    while True:
        rd = txtFile.readline()
        if len(rd) > x:
            longest = rd
            x = len(rd)
        elif rd == '':
            break
    txtFile.close()
    entr.delete(0, END)
    entr.insert(0, longest)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top