首页 > 解决方案 > 从 .txt 文件中检索输入

问题描述

使用下面的 .txt 文件,如何创建一个 tkinter GUI,它将获取 txt 文件并为每一行代码创建一个新框架。是否可以在每个页面上为它们制作单独的按钮?

#Hello.txt
 hi 
 hello
 here

标签: pythontkinter

解决方案


通常,您希望有一些代码示例来说明您正在尝试做什么以及您在哪里被困在这里提出问题。

然而,这并不难想象,我想建立一个例子。

在这里,我创建了一个具有 2 个按钮和一个标签的 GUI。我只需使用跟踪变量在下一个或上一个索引处更新标签。如果我到达列表的开头或列表的末尾,按钮将不会做任何事情,除了打印到控制台您已到达末尾。

这个例子应该作为你想要做的事情的一个很好的基础。

我的main.pypython 文件和我的data.txt文件在同一个目录中。

data.txt文件如下所示:

Row one in file.
Row two in file.
Row three in file.

代码是:

import tkinter as tk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.list_of_data_in_file = []
        self.ndex = 0
        with open("data.txt", "r") as data:
            # Readlines() will convert the file to a list per line in file.
            self.list_of_data_in_file = data.readlines()
        self.lbl = tk.Label(self, text=self.list_of_data_in_file[self.ndex])
        self.lbl.grid(row=0, column=1)

        tk.Button(self, text="Previous", command=self.previous).grid(row=0, column=0)
        tk.Button(self, text="Next", command=self.next).grid(row=0, column=2)

    def previous(self):
        # simple if statement to make sure we don't get errors when changing index on the list.
        if self.ndex != 0:
            self.ndex -= 1
            self.lbl.config(text=self.list_of_data_in_file[self.ndex])
        else:
            print("No previous index")

    def next(self):
        # simple if statement to make sure we don't get errors when changing index on the list.
        if self.ndex != (len(self.list_of_data_in_file) - 1):
            self.ndex += 1
            self.lbl.config(text=self.list_of_data_in_file[self.ndex])
        else:
            print("Reached end of list!")


if __name__ == "__main__":
    App().mainloop()

推荐阅读