How do I center a frame within a frame in Tkinter?

前端 未结 2 591
野的像风
野的像风 2021-01-12 08:05

I have a frame that I fixed the size of using the grid_propagate() method. I\'d like to center a frame within this frame. How do I go about this?

2条回答
  •  悲哀的现实
    2021-01-12 08:46

    pack it to fill in all directions. Add padding as needed.

    Or, use place which lets you use relative or absolute positioning. You can use a relative x/y of .5/.5 and an anchor of "c" (center).

    import Tkinter as tk
    
    root=tk.Tk()
    f1 = tk.Frame(width=200, height=200, background="red")
    f2 = tk.Frame(width=100, height=100, background="blue")
    
    f1.pack(fill="both", expand=True, padx=20, pady=20)
    f2.place(in_=f1, anchor="c", relx=.5, rely=.5)
    
    root.mainloop()
    

提交回复
热议问题