0

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

1 回答 1

1

问题是您关闭文件并显示最长行的代码永远不会执行:

    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跳出 while 循环,由于后面没有代码,Python 从函数返回。将最后三行移出while-loop,您应该会很好:

    # 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)
于 2013-09-10T13:17:47.890 回答