简体   繁体   中英

Why wont my grid_columnconfigure work on this tkinter code?

Just started learning tkinter and im tackling on grid management. I set the a frame to have 1 weight on column 0, therefore I expected label1 to be stretched to the end of the frame, then label2 added on column 1 with the length relative to its text size.

expected output: https://gyazo.com/65cf907e2cdea07d08844bdc8c62c7b2

output: https://gyazo.com/3c9e9c9f86372e01e96283545387c51e

Heres my code:

import tkinter as tk


class App(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, *kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        frame_list = (MenuFrame,
                     )

        self.geometry("1024x768")
        self.frames = {}

        for F in frame_list:
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("MenuFrame")

    def show_frame(self, page_name):
        frame = self.frames[page_name]
        frame.tkraise()


class MenuFrame(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.create_widgets(self)

    def create_widgets(self, parent):

        frame = tk.Frame(self, bg="white")
        frame.grid_columnconfigure(0, weight=1)
        frame.grid_rowconfigure(0, weight=1)

        label1 = tk.Label(frame, text="Label one", bg="red")
        label2 = tk.Label(frame, text="Label two", bg="blue", fg="white")

        frame.grid(row=0, column=0, sticky="nsew")
        label1.grid(row=0, column=0)
        label2.grid(row=0, column=1)
  

if __name__ == "__main__":
    app = App()
    app.mainloop()

You are properly configuring the weight for frame . However, frame hasn't been properly configured to fill the window. Because of that, it's just barely wide enough for the two labels and thus the weight has no effect.

Since frame seems to be the only widget inside the class MenuFrame , I would use pack instead of grid since it only requires one line:

frame.pack(fill="both", expand=True)

If you prefer using grid , then you need to also configure the weight for its parent.

self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
frame.grid(row=0, column=0, sticky="nsew")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM