首页 > 解决方案 > 这个循环每次循环都会创建一个全新的标签......为什么?

问题描述

每次循环它都会创建一个全新的标签,而不是刷新。

from tkinter import *
import psutil

def task():
   e = Entry(root)
   e.pack()

   e.delete(0, END)
   e.insert(0,psutil.cpu_percent(interval=None))
   s = e.get()
   root.after(500, task)  # reschedule event in .5 seconds


root = Tk()
root.after(500, task)
root.mainloop()

标签: pythontkinter

解决方案


Because every time you call the task function, it creates a new Entry object and deletes the content of the new object instead of using one global Entry.

First of all create the entry:

root = Tk()
e = Entry(root)
e.pack()

Then make sure that your task function is using the one and only global Entry e without creating any new ones:

def task():
    e.delete(0, END)
    e.insert(0, psutil.cpu_percent(interval=None))
    root.after(500, task)

and then you can call the function and let it call itself.


推荐阅读