Home > OS >  tkinter, csv file, auto update
tkinter, csv file, auto update

Time:10-05

I want help with this please, I want to reflect the change on the csv file immediately without closing the window. in other words, I want a live update to the window each time someone adds or changes something in the csv file.

import csv

root=Tk()
root.geometry('500x500')
with open('FILE.csv') as file:
    reader = csv.reader(file)
    for row in reader:
        
        label= Label(root, text=row)
        label.pack()
root.mainloop()

CodePudding user response:

Start by writing a function that does nothing but refresh the screen. Then, write another function that checks to see if the file has changed and calls the refresh function if it has. Finally, arrange for that function to be called once a second.

To make it easier to delete the old data, put the labels in a dedicated frame. Then, you can easily iterate over all of the children to remove the old data.

In the following example, the data will appear in csv_frame. The function to refresh the frame is named refresh, and it takes the name of the file to be read. The function auto_refresh also takes the name of a file, and the mtime (modified time) when it last caled refresh. It will check to see if the current mtime has changed, and call refresh if it has. It then schedules itself to be run again in one second. Setting the initial mtime to -1 forces auto_refresh to call refresh the first time.

import tkinter as tk
import os.path
import csv

def refresh(filename):

    for child in csv_frame.winfo_children():
        child.destroy()

    with open(filename) as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            label = tk.Label(csv_frame, text=", ".join(row))
            label.pack(side="top", anchor="w")

def auto_refresh(filename, last_mtime=-1):
    mtime = os.path.getmtime(filename)
    if mtime > last_mtime:
        refresh(filename)
    root.after(1000, auto_refresh, filename, mtime)

root = tk.Tk()
csv_frame = tk.Frame(root)
csv_frame.pack(side="top", fill="both", expand=True)

auto_refresh("/tmp/FILE.csv")

root.mainloop()

  • Related