如何读取txt文件并解析数据以在tkinter GUI中显示

2024-04-26 20:44:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python很陌生,需要一些帮助。我需要从一个txt文件中读取所有的值并将其显示到GUI中。 我选择的txt文件作为操作所需的文件,因此我选择一个文本文件存储字典。 我使用的是python3,非常感谢您的帮助。你知道吗

from tkinter import *
#read the file
file = open("./ppl.txt", "r")
courses = file.readlines()
print(courses)

root = Tk()

for course in courses:
    temp_text = courses
    Label(root, text=temp_text).pack()

mainloop()

txt文件(ppl.txt)是:

people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
          2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}

现在,GUI显示了一个混乱的格式:

scrrenshot of messy output being displayed

我希望以GUI为例:

Name: John, Age:27, Sex: Male
Name: Marie, Age:22, Sex: Female

Tags: 文件textnametxtageguirootjohn
1条回答
网友
1楼 · 发布于 2024-04-26 20:44:51

这里有一种方法,使用内置的^{}函数执行文本文件,就像它是Python模块一样,并返回模块globals dictionary,这对于不受信任的输入是一种潜在的安全隐患。你知道吗

在文本文件中执行代码后,它将获得定义的dictionary对象,并将其内容格式化为行列表,这些行随后用于生成Label小部件。你知道吗

import runpy
from tkinter import *

filepath = "./ppl.txt"

# Execute file as python module and get the module globals dictionary defined.
mod_dict = runpy.run_path(filepath, {'__builtins__': None})
people = mod_dict['people']  # Retrieve dictionary defined.

# Format dictionary data into separate lines.
lines = []
for person in people.values():
    line = ', '.join('{}: {}'.format(key, value) for (key, value) in person.items())
    lines.append(line)

root = Tk()

for line in lines:
    Label(root, text=line).pack(anchor=W)

mainloop()

结果:

screenshot of data displayed in tkinter window

相关问题 更多 >