I have a text file which contains four words line by line. suppose for example:
cat
mat
rat
hat
I want to show these words in an Entry widget. Like "cat" in first Entry widget, "mat" in second Entry widget and so on so. Now, if I update the contents of any Entry widget then it should also auto update in the text file. I wrote some codes to display Entry widgets but after that am not getting how to achieve this?
from tkinter import *
top = Tk()
with open('C:/Users/jaykr/Desktop/data.txt') as file:
data = file.read().split("\n")
for i in range(len(data)):
Entry(top).grid(row=i, column=0)
top.mainloop()
You can take advantage of tkinter's StringVar
variable class and its trace()
method. Here is an MCVE:
import tkinter as tk
root = tk.Tk()
entry_var = tk.StringVar()
entry = tk.Entry(root, width=10, textvariable=entry_var)
entry.pack()
def autoupdate(*args):
with open('test.txt', 'w') as f:
f.write(entry_var.get())
entry_var.trace('w', autoupdate)
root.mainloop()