Search code examples
pythontkinterframedimensions

Tkinter frame has dimensions different from dimensions given to and idk why


I'm struggling with Tkinter now. I wanted to create layout but if I define window dimensions (800x600) and create frame which have to be wide 800 too, it have just half.

I tried googling and changing code, if I multiply width 2 times (to 1600) then frame fit the screen perfetly.

Here is code:

import tkinter as tk

SW, SH = 800, 600

win = tk.Tk()
win.geometry(f"{SW}x{SH}")

frm_appname = tk.Frame(
    master = win,
    bg = 'red'
)

frm_appname.place(
    anchor = tk.N,
    width = 800,
    relheight = (1/6)
)

Here is output: enter image description here

Can anyone explain me what happened here?


Solution

  • The anchor of "n" (tk.N) means that the top center portion of the frame is at the given coordinate. Since you didn't provide an x and y coordinate for place it defaults to 0,0. So, the top/middle (400,0) of the frame is at coordinate 0,0.

    If you set the anchor to "n" or tk.NW, the top-left corner of your frame will be in the top-left corner of the window.


    On an unrelated note, experience has taught me that layouts are nearly always easier to create with pack and/or grid. In my coupe of decades of using tk and tkinter, I've never used place for more than one or two special-case widgets.