May-22-2023, 12:30 PM
Sorry, I answered the wrong question again.
To place a frame in the middle of the window, use "frame.place(relx=0.5, rely=0.5, anchor=tk.CENTER)".
To place a frame in the middle of the window, use "frame.place(relx=0.5, rely=0.5, anchor=tk.CENTER)".
import tkinter as tk import random class FramedLabel(tk.Frame): """A label with a frame. Looks suspiciously like a button.""" def __init__( self, parent, text="", relief=tk.RAISED, borderwidth=4, font=(None, 10), width=10, height=3, **kwargs): super().__init__( parent, relief=relief, borderwidth=borderwidth, **kwargs ) self.label = tk.Label( self, text=text, font=font, width=width, height=height ) self.label.pack() def set_color(self, color): self["bg"] = color self.label["bg"] = color class MyWindow(tk.Tk): def __init__(self): super().__init__() self.title("Feed Bins") self.geometry("800x400") frame = tk.Frame(self) frame.place(relx=0.5, rely=0.5, anchor=tk.CENTER) self.labels = [ FramedLabel(frame, text=f"Bin {x}") for x in range(1, 16) ] for x, label in enumerate(self.labels): label.grid(row=x // 5, column=x % 5, padx=5, pady=5) label.set_color("lightgrey") button = tk.Button(frame, text="Update", command=self.check_alerts) button.grid(row=4, column=0, columnspan=5, sticky="news") def check_alerts(self): for label in self.labels: label.set_color(random.choice(("red", "lightgrey"))) MyWindow().mainloop()However, I prefer to pack the frame and set the borders to expand the window to the desired size.
import tkinter as tk import random class FramedLabel(tk.Frame): """A label with a frame. Looks suspiciously like a button.""" def __init__( self, parent, text="", relief=tk.RAISED, borderwidth=4, font=(None, 10), width=10, height=3, **kwargs): super().__init__( parent, relief=relief, borderwidth=borderwidth, **kwargs ) self.label = tk.Label( self, text=text, font=font, width=width, height=height ) self.label.pack() def set_color(self, color): self["bg"] = color self.label["bg"] = color class MyWindow(tk.Tk): def __init__(self): super().__init__() self.title("Feed Bins") frame = tk.Frame(self) frame.pack(padx=100, pady=100) self.labels = [ FramedLabel(frame, text=f"Bin {x}") for x in range(1, 16) ] for x, label in enumerate(self.labels): label.grid(row=x // 5, column=x % 5, padx=5, pady=5) label.set_color("lightgrey") button = tk.Button(frame, text="Update", command=self.check_alerts) button.grid(row=4, column=0, columnspan=5, sticky="news") def check_alerts(self): for label in self.labels: label.set_color(random.choice(("red", "lightgrey"))) MyWindow().mainloop()Either way, the real trick is to create a frame that holds your labels and buttons. Pack (or grid) the labels and buttons in the frame. Place or pack the frame in the window