Home > Software engineering >  sticky does not work in a frame in Tkinter
sticky does not work in a frame in Tkinter

Time:11-16

I tried to use sticky to make b_frame take half of a_frame , and c_frame also take half of a_frame. Each frame use half of a_frame. Sum of c_frame and b_frame will use the whole width of a_frame. But it does not work as I expected.

a_frame=tk.Frame(frame, highlightbackground="red",
                         highlightthickness=2)
a_frame.grid(row=3, column=0, sticky="nsew", columnspan=2)


b_frame = tk.LabelFrame(a_frame, text="b")
        b_frame.grid(row=0, column=0, sticky="nsw")

c_frame = tk.LabelFrame(a_frame, text="c")
      c_frame.grid(row=0, column=0, sticky="nse")

d = tk.Entry(b_frame)
        d.grid(row=0, column=0)

e = tk.Entry(e_frame)
        d.grid(row=0, column=0)

The result

CodePudding user response:

You need to add a_frame.columnconfigure((0,1), weight=1) to make b_frame (in column 0) and c_frame (in column 1) to share the horizontal space of a_frame equally:

a_frame=tk.Frame(frame, highlightbackground="red", highlightthickness=2)
a_frame.grid(row=3, column=0, sticky="nsew", columnspan=2)

# make column 0 and 1 to share horizontal space of a_frame equally
a_frame.columnconfigure((0,1), weight=1)

b_frame = tk.LabelFrame(a_frame, text="b")
b_frame.grid(row=0, column=0, sticky="ew")

c_frame = tk.LabelFrame(a_frame, text="c")
c_frame.grid(row=0, column=1, sticky="ew") # changed column=0 to column=1

d = tk.Entry(b_frame)
d.grid(row=0, column=0)

e = tk.Entry(c_frame)
e.grid(row=0, column=0)

enter image description here

CodePudding user response:

You had some bad type error.

Try this:

import tkinter as tk
root= tk.Tk()

a_frame=tk.Frame(root, highlightbackground="red",
                         highlightthickness=2)
a_frame.grid(row=0, column=0,  sticky="nw", columnspan=3)


b_frame = tk.LabelFrame(a_frame, text="b")
b_frame.grid(row=0, column=0, sticky="nw")

c_frame = tk.LabelFrame(a_frame, text="c")
c_frame.grid(row=0, column=1,sticky="nw")

d = tk.Entry(b_frame)
d.grid(row=0, column=0, sticky="nw")

e = tk.Entry(c_frame)
e.grid(row=0, column=1,  sticky="nw")

root.mainloop()

Result:

enter image description here

  • Related