我在使用 after() 和 destroy() 方法时遇到问题。我在监控 ram 状态和处理器状态时创建了一个 meniu。当我调用第一个 def 时,没关系,但是当我调用第二个 def 时,示例处理器状态,帧内的信息会显示几毫秒,然后是有关 ram 状态的信息,一遍又一遍。
https://i.stack.imgur.com/JPZoj.gif
def ram():
root.after(1000,ram)
for widget in app.winfo_children():
widget.destroy()
iram = psutil.virtual_memory()
total = iram.total / (1024*1024)
available = iram.available /(1024*1024)
percent = iram.percent
used = iram.used /(1024*1024)
inf = Label(app, text="Information about RAM status")
inf.grid(row=0,column=1, pady=10)
total_1 = Label(app, text="Total memory RAM")
total_1.grid(row=1,column=0)
total1 = Label(app, text=total,fg="blue")
total1.grid(row=1, column=1,pady=5)
available_1 = Label(app, text="Available memory RAM")
available_1.grid(row=2,column=0)
available1 = Label(app, text=available,fg="blue")
available1.grid(row=2, column=1,pady=5)
percent_1 = Label(app, text="Used memory RAM in %")
percent_1.grid(row=3,column=0)
percent1 = Label(app, text=percent,fg="red")
percent1.grid(row=3, column=1,pady=5)
used_1 = Label(app, text="Used memory RAM")
used_1.grid(row=4,column=0)
used1 = Label(app, text=used,fg="blue")
used1.grid(row=4, column=1,pady=5)
def help():
for widget in app.winfo_children():
widget.destroy()
help_1=Label(app, text="This aplication was created with Python 3.5 n")
help_1.grid(row=0,column=0)
root = Tk()
app = Frame(root)
app.grid()
root.title("S.M.A.R.T.")
root.geometry("500x300")
root.resizable(0,0)
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Battery Status", command=battery_status)
filemenu.add_command(label="Disk's Status", command=disk_status)
filemenu.add_command(label="Processor Status", command=processor)
filemenu.add_command(label="PC's Status", command=pc)
filemenu.add_command(label="RAM's Status", command=ram)
filemenu.add_command(label="Windows Status", command=windows)
filemenu.add_command(label="Exit", command=root.quit)
filemenu.add_separator()
menubar.add_cascade(label="File", menu=filemenu)
helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help", command=help)
menubar.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_separator()
root.config(menu=menubar)
root.mainloop()
root.destroy()
我应该怎么做才能避免这个问题?因为它会回忆起那些子菜单,并且无法理解框架中的信息。
问题尚不清楚,但我认为您要问的是当您请求不同的信息时如何停止更新旧信息。
after
返回一个标识符,您可以将其传递给after_cancel
以防止再次调用该函数。因此,您的菜单命令只需在计划新作业之前取消任何挂起的作业。
它看起来像这样:
global after_id
after_id = None
...
def cancel_old_job():
global after_id
if after_id is not None:
root.after_cancel(after_id)
after_id = None
...
def ram():
global after_id
cancel_old_job()
after_id = root.after(1000,ram)
...
def pc():
global after_id
cancel_old_job()
after_id = root.after(1000,pc)
...
...