简体   繁体   中英

Reading txt file and adding the contents to a Tkinter Listbox Python

I am wondering how one adds the contents of a .txt file to a Tkinter Listbox ?

Let's say I had a file called test.txt and I wanted to add the contents of it to a Listbox named Lb , how would I do it? Below is an example of what I have tried - to help you understand the question!

Contents of test.txt :

Apple
Cherry
Beetroot

My Code:

from tkinter import *
root = Tk()

Lb = Listbox(root)
Lb.grid()
f = open("test.txt","r")
for x in f:
    Lb.insert(END,x)
    print(x)
f.close()

The Traceback is blank, showing the file is not opening properly, but I don't know where I have an error in my code. The Listbox should contain apple, cherry and beetroot on seperate lines/entries. But it is completely blank, likely because there was no Traceback from above, seeming as the .txt file wasn't opening properly. What have I done wrong? And how can I correct my code to do as I explained in the beginning of my answer?

Thank you for your answers in advance!

What Bryan said. Add root.mainloop() to the end to keep your application running:

from tkinter import *

root = Tk()
Lb = Listbox(root)
Lb.grid()
f = open("test.txt","r")
for x in f:
    Lb.insert(END,x)
    print(x)
f.close()
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM