Buttons not being placed inside the correct frame in tkinter

Question:

I am a newbie trying to use tkinter to build a GUI for an application. So far, I have a frame that I’d like to put several buttons into. However, every time I attempt to position this button, it isn’t placed properly, being put outside of the frame itself. I wouldn’t like to use the place function because of the several buttons I have to dynamically generate coming from an excel sheet so I was hoping to use the grid function instead.

Here is what I have so far

from tkinter import *
from customtkinter import *

window = Tk()
window.geometry("1920x1080")
window.state("zoomed")
window.title("My Company's Description Printer")

main_frame = CTkFrame(window, width=1920, height=1080, fg_color="grey21")
main_frame.place(x=0, y=0)

title = Label(main_frame,
              text="My Company",
              bg="grey21",
              fg="white",
              font=("Trajan Pro", 20)).place(x=626, y=30)

button_frame = CTkCanvas(main_frame,
                         width=800,
                         height=600,
                         highlightthickness=3,
                         highlightbackground="black",
                         relief="ridge",
                         bg="grey19").place(x=60, y=110)

test_button = CTkButton(button_frame, text="test").grid(row=0, column=0)

window.mainloop()

Example of code being ran

As you can see, the button is being placed in the top left corner of the entire window rather than the top left corner of the black bordered button frame. Any help would be appreciated. Thank you so much.

Asked By: Patrick Rodriguez

||

Answers:

Note that button_frame is None because it is the result of .place(...), so the button (test_button is None as well due to same reason) is a child of the root window instead of the instance of CTkCanvas. .place(...) should be called in separate line.

Also .create_window() is used instead of tkinter layout manager to put widget into a canvas:

...
button_frame = CTkCanvas(main_frame,
                         width=800,
                         height=600,
                         highlightthickness=3,
                         highlightbackground="black",
                         relief="ridge",
                         bg="grey19")
# call .place(...) in separate line
button_frame.place(x=60, y=110)

test_button = CTkButton(button_frame, text="test") # don't use .grid(row=0, column=0)
# use .create_window() to put widget into canvas
button_frame.create_window(0, 0, window=test_button, anchor="nw")
Answered By: acw1668