python - 这个循环每次循环都会创建一个全新的标签......为什么?
问题描述
每次循环它都会创建一个全新的标签,而不是刷新。
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()
解决方案
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.
推荐阅读
- rabbitmq - 在 AMQP 0.9 (rabbitmq) 中 app_id 和 cluster_id 字段是什么
- python - Python:while循环中“else”的目的
- gmail-addons - Gmail 插件 - 在多个线程中使用 getMessages() 时“缺少访问令牌”(但对于当前消息的线程来说很好)
- azure - 如何使用 MongoDB API 将 Azure Databricks 连接到 Cosmos DB?
- c# - ASP.NET核心webapi中的Tryvalidatemodel在单元测试中抛出空引用异常
- ios - 如何在 Swift 中使用 Alamofire 时将 JSON 响应存储到缓存中
- unix - shell中的命令在“-”之后获取第二个数值
- web2py - 301将带有斜杠的网址重定向到不带斜杠的网址web2py
- kotlin - 奇怪的 Kotlin 零安全行为
- javascript - Highcharts 在可拖动的折线图上重绘和排序数据