Home > Mobile >  How to get a tkinter canvas to the center of the available space
How to get a tkinter canvas to the center of the available space

Time:05-12

I am trying to get the canvas to center of the available space but it keeps sticking to North part of the screen... Here is an imageHere

And here is the code

def newsetup(filelocation):
    global width, height
    global stage, img_id, imgtk
    
    for widgets in root.winfo_children():
        widgets.destroy()

    root.config(bg = '#454545')
    iconsframewidth = int(screen_width / 20)
    
    iconsframe = Frame(root, width = iconsframewidth, bg = '#2a2a2a')
    iconsframe.pack(side = 'left', expand = False, fill = 'y')
    iconsframe.pack_propagate(0)
    sep1frame = Frame(root, bg = '#1a1a1a', width = 10, relief = 'sunken')
    sep1frame.pack(side = 'left', expand = False, fill = 'y')
    optionsframe = Frame(root, bg = '#2a2a2a', height = 100)
    optionsframe.pack(side = 'top', expand = False, fill = 'x')
    optionsframe.pack_propagate(0)
    sep2frame = Frame(root, bg = '#1a1a1a', height = 10, relief = 'sunken')
    sep2frame.pack(side = 'top', expand = False, fill = 'x')
    propertyframe = Frame(root, bg = '#2a2a2a', width = 150)
    propertyframe.pack(side = 'right', expand = False, fill = 'y')
    propertyframe.pack_propagate(0)
    sep3frame = Frame(root, bg = '#1a1a1a', width = 10, relief = 'sunken')
    sep3frame.pack(side = 'right', expand = False, fill = 'y')
    stageframe = Frame(root, bg = '#454545')
    stageframe.pack(side = 'top', expand = True, fill = 'both')
    stageframe.pack_propagate(0)

    stage = Canvas(stageframe, width = width, height = height)
    stage.pack(anchor = CENTER)

    root.update()

    pencilbutton = Button(iconsframe, image = pencilimg, borderwidth = 0, bg = '#2a2a2a', fg = '#2a2a2a', relief = 'flat')
    pencilbutton.pack(anchor = W)

    imgtk = ImageTk.PhotoImage(Image.open(filelocation)) 
    img_id = stage.create_image(stage.winfo_width() / 2, stage.winfo_height() / 2, image = imgtk)
    stage.image = imgtk

    stage.bind('<Configure>', PhotoEditing.stageresize)

I have tried using anchors it has not worked... I have an idea put the canvas in the frame but the frame does not fill the entire blank area

CodePudding user response:

TL;DR add expand=True when packing the canvas.

The packer works by placing widgets along one side of the available empty space, and centers it in the space that is allocated. By default the allocated space will be as small as possible to fit the widget.

When packing something along the top or bottom, if you want it to be in the center vertically you need to tell the packer to expand the space allocated to be all of the remaining space. The widget will then be centered both horizontally and vertically in the remaining space.

I also recommend to always explicitly set the side so that it's more obvious what your intent is.

stage.pack(side="top", anchor = CENTER, expand=True)
  • Related