Search code examples
pythonuser-interfacetkintergridframe

Can't fit more than one Label in a Frame using grids with Tkinter


I am making a widget to show the weather. I am trying to fit multiple Labels within a frame with the grid tool. The first Label I insert in the grid seem to take all the place. No matter what I do, the second label keep getting stuck outside the Frame like so: TKinter UI image

import tkinter as tk

class App:
    
    def __init__(self, root):
        self.root = root
        self.root.resizable(False, False)
        self.root.geometry('1920x1080')
        self.root.configure(bg='#4F6367')

        self.weather = Containers(root, 'Weather', 1200, 130)
        self.weather.grid(pady=50, padx=50)
        self.weather.grid_propagate(0)
        self.weather.columnconfigure(0, weight=1)
        self.weather.columnconfigure(1, weight=1)

        self.sun = tk.Label(self.weather, text='Sunrise time')
        self.sun.grid(row=1, column=0)
        self.sun2 = tk.Label(self.weather, text='Sunset time')
        self.sun2.grid(row=1, column=1)

class Containers(tk.Frame):

    def __init__(self, root, name, width, height):
        super(Containers, self).__init__(root, width=width, height=height, bg='#F4F2F3')
        self.grid_propagate(0)
    #Container - Header
        self.label_frame = tk.Frame(self, width=width, height=20, bg='#754043')
        self.label_frame.grid_propagate(0)
        self.label_frame.grid(sticky='N')
    #Container - Header - Label
        self.label = tk.Label(self.label_frame, text=name, bg='#754043', fg='#F4F2F3')
        self.label.grid(sticky='WN')


if __name__ == "__main__":
    root = tk.Tk()
    user_interface = App(root)
    root.mainloop()

It's my first big TKinter project so the structure might not be ideal. Thanks.


Solution

  • You have two columns in the self.weather frame which means the self.label_frame should span two columns:

    #Container - Header
        self.label_frame = tk.Frame(self, width=width, height=20, bg='#754043')
        self.label_frame.grid_propagate(0)
        self.label_frame.grid(columnspan=2, sticky='N')
        # Span two columns --------^