Home > Software design >  Is there a way to make objects with for loops or something else?
Is there a way to make objects with for loops or something else?

Time:10-15

I am trying to visualize a binary search algorithm and i need to create 10 "pillars" with tkinter. I am doing it this way (code below), but i have a feeling that there is a better way to do the same thing. I have already tried making the pillars with a for loop and exec command but i didn't seem to get it working.

import tkinter as tk


class MainWindow(tk.Tk):
    def __init__(self):
        super().__init__()
        self.geometry("1000x600")
        self.resizable(False, False)
        self.title("Binary Search Algorithm")

        self.p0 = tk.Label(self, text=f"I am pillar 0", bg="grey")
        self.p1 = tk.Label(self, text=f"I am pillar 1", bg="grey")
        self.p2 = tk.Label(self, text=f"I am pillar 2", bg="grey")
        self.p3 = tk.Label(self, text=f"I am pillar 3", bg="grey")
        self.p4 = tk.Label(self, text=f"I am pillar 4", bg="grey")
        self.p5 = tk.Label(self, text=f"I am pillar 5", bg="grey")
        self.p6 = tk.Label(self, text=f"I am pillar 6", bg="grey")
        self.p7 = tk.Label(self, text=f"I am pillar 7", bg="grey")
        self.p8 = tk.Label(self, text=f"I am pillar 8", bg="grey")
        self.p9 = tk.Label(self, text=f"I am pillar 9", bg="grey")

        self.p0.place(x=0, y=500)
        self.p1.place(x=100, y=500)
        self.p2.place(x=200, y=500)
        self.p3.place(x=300, y=500)
        self.p4.place(x=400, y=500)
        self.p5.place(x=500, y=500)
        self.p6.place(x=600, y=500)
        self.p7.place(x=700, y=500)
        self.p8.place(x=800, y=500)
        self.p9.place(x=900, y=500)

    if __name__ == "__main__":
        Display = MainWindow()
        Display.mainloop()

CodePudding user response:

Yes, keep a single list or dict of labels, rather than a number of separate attributes.

def __init__(self):
    super().__init__()
    self.geometry("1000x600")
    self.resizable(False, False)
    self.title("Binary Search Algorithm")
    
    self.ps = []
    for i in range(10):
        p = tk.Label(self, text=f"I am pillar {i}", bg="grey")
        p.place(x=100*i, y=500)
        self.ps.append(p)

In the rest of the code, you would replace (e.g.) self.p0 with self.ps[0], and similarly for the other numbers attributes.

CodePudding user response:

Yes, you could do something like

for i, x in enumerate(x_values):
   setattr(self, f'p{i}', x)

Although, I don't know what tkinter requires, but I would rethink the logic.

  • Related