我创建了一个脚本,动态地添加/删除/更新窗口中的标签。唯一的问题是旧框架的标签没有消失..这会导致标签在窗口背景中干扰,当然也会导致某种内存泄漏(不确定这里是否使用正确的术语)。
这是我的代码:
这里是一些屏幕截图:
连接了3个设备,则显示3个标签: 连接了2个设备,则显示2个标签: 新标签在旧标签上方:
这是我的代码:
import tkinter as tk
from tkinter.ttk import *
from subprocess import call,Popen,PIPE, STDOUT
class App():
def __init__(self):
self.root = tk.Tk()
self.root.title("devices networks")
self.update_clock()
self.root.mainloop()
def update_clock(self):
i=0
adb_absolute_path = "C:\\Users\\ilan.MAXTECH\\AppData\\Local\\Android\\Sdk\\Platform-tools\\"
# Get the list of connected devices
cmd = adb_absolute_path+"adb.exe devices"
proc = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
device_list = proc.communicate()[0].decode().split("\r\n")
# remove unnecessary text in devices call
device_list.pop(0)
device_list.remove("")
device_list.remove("")
#### not working.... #######
# #erase the old labels ( in case a device has been disconected
# for line in range(10):
# lb = Label(self.root, text="")
# lb.grid(row=1, column=line)
###########################
#print netcfg for each device
for device in device_list:
#get the netcfg for specific device
device_serial = device.split("\t")[0]
cmd = adb_absolute_path + "adb.exe -s " + device_serial + " shell netcfg"
proc = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
netcfg_output = proc.communicate()[0].decode()
#add a new label to the screen
lb = Label(self.root, text=device_serial+"\n"+netcfg_output)
lb.grid(row=1, column=i)
lbblank = Label(self.root,text="\t\t")
lbblank.grid(row=1, column=i+1)
i += 2
self.root.geometry(str(device_list.__len__()*450)+"x700")
self.root.after(1000, self.update_clock)
app=App()
这里是一些屏幕截图:
连接了3个设备,则显示3个标签: 连接了2个设备,则显示2个标签: 新标签在旧标签上方:
StringVar
来实现推荐的方法。虽然可以使用,但并非必需。您还可以使用标签的configure
方法来更改显示的值。 - Bryan Oakleywidget.configure(...)
还是variable.set(...)
,但在这两种情况下,你都必须访问另一个对象。我认为使用单个对象控制你的显示比使用两个对象更加简洁。无论如何,回答这个问题的答案就像你所说的 - 不要重新创建标签,只需更新它们。 - Bryan Oakley