tkinter list of labels not displaying properly
You have used class variables
instead of instance variables
. There is only one set of class variables
for a class, so you overwrite the class variables
in each iteration.
Below is an example of using instance variables
:
class NetworkPort:
def __init__(self, master, num):
numFontsize = 10
self.num = Label(master, text=num, background='white', font=('Calibri', numFontsize), anchor='center')
self.indicator = Label(master, background='black')
ports = []
for i in range(24):
ports.append(NetworkPort(root, i+1))
y = 4 if i > 11 else 2
ports[i].num.place(relwidth=1/14, relheight=1/10, relx=(i%12+1)/14, rely=y/10)
ports[i].indicator.place(relwidth=1/14, relheight=1/10, relx=(i%12+1)/14, rely=(y+1)/10)
I've managed to adjust it so you maintain the original proportions of the GUI under a class based structure:
from tkinter import *
class NetworkPort:
def __init__(self, master):
self.master = master
master.geometry('400x225')
master.configure(background='white')
self.num_font_size = 10
# List to be populated with indicator widgets
self.widgets = []
x = -1
y = 0
for i in range(24):
# On 12 iteration move to new line (y), reset to first column (x)
if i == 12:
x = 0
y = 3
# Move to new column with each iteration
else:
x += 1
# Generate network port number
num = Label(master, background='white', text=i + 1, font=('Calibri', self.num_font_size), anchor='center')
num.place(relwidth=1 / 14, relheight=1 / 10, relx=(x + 1) / 14, rely=(y + 2) / 10)
# Generate network indicator label
indicator = Label(master, background='black')
indicator.place(relwidth=1 / 14, relheight=1 / 10, relx=(x + 1) / 14, rely=(y + 3) / 10)
# Add indicator label objects to list
self.widgets.append(indicator)
# Example of adjusting one specific indicators colour by accessing the widget list
self.widgets[3].config(bg='red')
if __name__ == "__main__":
root = Tk()
NetworkPort(root)
root.mainloop()
Hopefully that helps, feel free to query anything you're curious about.