我希望在列表中记录由函数生成的标签。这完全是为了稍后使用label.place_forget()来删除它们。因为当我调用这个函数的时候会产生很多标签,并且我调用这个函数很多次。我在函数外部创建了列表,然后在函数内部调用list.extend()将变量/标签添加到列表中。然而,当我打印列表时,在函数被调用之后,似乎存储了变量的内存位置。这是我的代码…
import sys, tkinter, csv
from tkinter import *
playerRows = []
def playerTab(team, name, pos, pts, reb, ast, stl, blk, to, y):
global playerRows
#Print the team
playerTeam = Label(statWindow, bg = "white", text = team)
playerTeam.config(height = 1, width = 13)
playerTeam.place(x=20,y=y)
#Print the name
playerName = Label(statWindow, bg = "white", text = name)
playerName.config(height = 1, width = 25)
playerName.place(x=119,y=y)
#Print the players position
playerPosition = Label(statWindow, bg = "white", text = pos)
playerPosition.config(height = 1, width = 4)
playerPosition.place(x=302,y=y)
#Print the players average points
playerPoints = Label(statWindow, bg = "white", text = pts)
playerPoints.config(height = 1, width = 4)
playerPoints.place(x=338,y=y)
#Print the players average rebounds
playerRebounds = Label(statWindow, bg = "white", text = reb)
playerRebounds.config(height = 1, width = 4)
playerRebounds.place(x=374,y=y)
#Print the players average assists
playerAssists = Label(statWindow, bg = "white", text = ast)
playerAssists.config(height = 1, width = 4)
playerAssists.place(x=410,y=y)
#Print the players average steals
playerSteals = Label(statWindow, bg = "white", text = stl)
playerSteals.config(height = 1, width = 4)
playerSteals.place(x=446,y=y)
#Print the players average blocks
playerBlocks = Label(statWindow, bg = "white", text = blk)
playerBlocks.config(height = 1, width = 4)
playerBlocks.place(x=482,y=y)
#Print the players average turnovers
playerTurnovers = Label(statWindow, bg = "white", text = to)
playerTurnovers.config(height = 1, width = 4)
playerTurnovers.place(x=518,y=y)
playerRows.extend((playerTeam, playerName, playerPosition, playerPoints, playerRebounds, playerAssists, playerSteals, playerBlocks, playerTurnovers))
return playerTeam, playerName, playerPosition, playerPoints, playerRebounds, playerAssists, playerSteals, playerBlocks, playerTurnovers
playerTab(row['Team'], (row['First Name'] + ' ' + row['Last Name']), row['Position'], row['Average PTS'], row['Average REB'], row['Average AST'], row['Average STL'], row['Average BLK'], row['Average TO'], 120)
当我调用print来打印列表时,我可以看到添加到列表中的值是…
[(<tkinter.Label object at 0x00000000035E8F28>, <tkinter.Label object at 0x00000000035E8B70>, <tkinter.Label object at 0x00000000035E8BE0>)]
因此,我如何保存列表中的标签,以便我可以在以后引用它们以删除它们
由于您的列表包含小部件实例,并且由于您没有显式地转换为字符串,因此python必须隐式地将对象转换为字符串。当它这样做时,它将打印一个类似<tkinter.Label object at 0x00000000035E8F28>
的标签。Python无法知道你真正想要的是"text"配置选项的值。
如果要打印标签文本,则必须为每行中的每个元素调用cget
方法:
for row in playerRows:
data = [label.cget("text") for label in row]
print(data)