0
import  psutil
import time
from tkinter import *


root = Tk()
Label = Label(root, text=psutil.cpu_percent()).pack()
time.sleep(1)
root.mainloop()

Here's the code. Now I want to refresh the psutil.cpu_percent() after 1 sec continuously. How can I make such a loop in it?

  • Don't use `time.sleep` when using `tkinter`. Also [this](https://stackoverflow.com/a/459131/11106801) will help you. – TheLizzard Sep 17 '22 at 11:45
  • 1
    You can do it in many different ways and there are plenty of examples on the web including this site. Most of them, however, using the tkinters `widget.after(ms,func)` method to achieve it. – Thingamabobs Sep 17 '22 at 11:50

1 Answers1

0

I didn't test it. Try this.

from tkinter import *
import  psutil

root = Tk()
def cpu_percent():
    Label(root, text=psutil.cpu_percent()).pack()
    root.after(1000, cpu_percent)

root.after(1000, cpu_percent)    
root.mainloop()
toyota Supra
  • 3,181
  • 4
  • 15
  • 19
  • 1
    It works thanks. but it should be from tkinter import * import psutil root = Tk() def cpu_percent(): Label(root, text=psutil.cpu_percent()).pack() root.after(1000, cpu_percent) root.after(1000, cpu_percent) root.mainloop() – Jahin Ahnaf Sep 17 '22 at 13:15
  • 1
    Right now you are creating a new `Label` each time it loops. Try creating a `Label` and then re-configuring it with the new `text`. – TheLizzard Sep 17 '22 at 13:21
  • 1
    In addition, the first `.after(..` seems unreasonable except you want to delay the shown output. – Thingamabobs Sep 17 '22 at 13:22
  • @TheLizzard., Thingamabobs. I don't have time to test. I know that Label. I will try to around around. – toyota Supra Sep 17 '22 at 13:34
  • @Jahin Ahnaf. Thank you for spotting it. – toyota Supra Sep 17 '22 at 14:23