Home > Net >  Frame doesn't get displayed in tkinter
Frame doesn't get displayed in tkinter

Time:01-21

import tkinter as tk

window = tk.Tk()

test_frame = tk.Frame()
testlabel = tk.Label(text="testLabel", master = test_frame)
test_frame.grid(row=0,column=0)

text_area = tk.Text()
text_area.grid(row=0,column=1)

window.mainloop()

I am learning python GUI and was trying a project on my own. I started with trying to distribute the window into sections(row and columns) and then putting the widgets in them. I made a frame and a text box and tried to fit them side by side, so I decided to put them in a 1x2 grid(1 row 2 columns). The problem is the text box shows up but the frame doesn't, I even added a test label to see the frame but it just doesn't show up. I have tried to width and height as well but it doesn't work.

Please show me what's missing.

Thank you.

CodePudding user response:

You do it wrong way. Add test_frame every widgets. Missing testlabel.grid(..) Code :

import tkinter as tk

window = tk.Tk()

test_frame = tk.Frame(window)
testlabel = tk.Label(test_frame, text="testLabel")
testlabel.grid(row=1, column=0)
test_frame.grid(row=0,column=0)

text_area = tk.Text(test_frame)
text_area.grid(row=2,column=0)

window.mainloop() 

Edit: screenshot:

enter image description here

CodePudding user response:

All you're really missing is placing the label on the frame, just pack or grid your test label just like you do with the frame or the textbox:

import tkinter as tk

window = tk.Tk()

test_frame = tk.Frame()
test_label = tk.Label(test_frame, text="testLabel")
test_label.pack()  # this is what you're missing
test_frame.grid(row=0, column=0)

text_area = tk.Text()
text_area.grid(row=0, column=1)

window.mainloop()

CodePudding user response:

My solution is to use 'place', because with grid, or pack(side='left') the Text widget doesn't respect the interface, it must be some default configuration, but with place I managed to leave one next to the other.

import tkinter as tk

# root
root = tk.Tk()
root.geometry('500x500')
# frame
frame = tk.Frame(root)
frame.pack(fill='both', expand=True)
# label
label = tk.Label(frame, text='Test', bg='red')
label.place(relx=0, rely=0, relwidth=0.5, relheight=1)
# text frame
text = tk.Text(frame, bg='light blue')
text.place(relx=0.5, rely=0, relwidth=0.5, relheight=1, )

if __name__ == '__main__':
    root.mainloop()

Example

  • Related