I want the data read with pandas updated every 1 second in the tkinter window. Instead, the display window shows the data of the successively inserted lines one below the other. How to change it?
import time
import pandas as pd
from tkinter import Tk, Label
root = Tk()
df =pd.read_csv('ab.csv')
for i , row in df.iterrows():
time.sleep(1)
a = row[2],row[3],row[4]
print(a)
root.title('Generator')
root.geometry("900x200")
label = Label(root, text=a, font=30, fg="black")
# root.update_idletasks()
root.update()
label.pack()
root.mainloop()
CodePudding user response:
pandas DataFrame.iterrows is an iterator which means you can call pythons built in next on it. What you do is to iterate over the whole dataframe and then start to show the content, which obviously ends up in the content last yielded by the iterator.
To have the effect of watching the iterator in tkinter you can use tcl after method as kind of coroutine that is built into python tkinter.
All together, your code should look like:
import pandas as pd
from tkinter import Tk, Label
def animated_content():
try:
#try to get next row
_, row = next(iterator)
a = row[2],row[3],row[4]
label.configure(text=a)
except StopIteration:
#if iterator comes to an end
print('dataframe is exhausted')
else:
#try another one in 1000ms
root.after(1000, animated_content)
iterator =pd.read_csv('ab.csv').iterrows()
root = Tk()
root.title('Generator')
root.geometry("900x200")
label = Label(root, fg="black")
label.pack()
animated_content()#start animation
root.mainloop()
CodePudding user response:
You have to use the universal after(x, func)
method to repeat func
after x
milliseconds. You also have to use config
method to change the text of the existing label rather than creating a new one over and overt again.
import pandas as pd
from tkinter import Tk, Label
root = Tk()
root.title('Generator')
root.geometry("900x200")
def repeat():
df = pd.read_csv('ab.csv')
for i, row in df.iterrows():
a = row[2], row[3], row[4] # Safe if converted a string instead
# Get the current label from the list and update its text
lbls[i].config(text=a)
root.after(1000, repeat) # Call repeat after 1000 ms
df = pd.read_csv('ab.csv')
lbls = []
for i, row in df.iterrows():
a = row[2], row[3], row[4] # Safe if converted a string instead
print(a)
label = Label(root, text=a, font=30, fg="black")
label.pack()
# Append the labels to a list to be able to edit them later in order
lbls.append(label)
root.after(1000, repeat) # Call repeat after 1000 ms
root.mainloop()