简体   繁体   English

读取 txt 文件并将内容添加到 Tkinter 列表框 Python

[英]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 ?我想知道如何将.txt文件的内容添加到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?假设我有一个名为test.txt的文件,我想将它的内容添加到名为Lb的列表框中,我该怎么做? Below is an example of what I have tried - to help you understand the question!以下是我尝试过的示例 - 帮助您理解问题!

Contents of test.txt : 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. Traceback 为空白,显示文件未正确打开,但我不知道我的代码在哪里出错。 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.但它完全是空白的,可能是因为上面没有 Traceback,似乎.txt文件没有正确打开。 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:root.mainloop()添加到末尾以保持应用程序运行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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