[Solved] Retrieving input from a .txt file [closed]


Generally you want to have some code example of what it is you are trying to do and where you are stuck to ask a question here.

However this was not hard to visualize and I felt like building an example.

Here I have created a GUI that has 2 buttons and one label. I simply update the label at the next or previous index by using a tracking variable. If I reach the beginning of the list or end of the list the buttons will not do anything except print to console that you have reached the end.

This example should serve as a good foundation for what you are trying to do.

I have my main.py python file and my data.txt file in the same directory.

The data.txt file looks like this:

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

The code is:

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

solved Retrieving input from a .txt file [closed]