0

I don't know if it's a duplicate question or not but I really want to be able to resize placed tkinter widgets when window is resized using .place() only. I know that I can use .grid() for this but to me grid() is confusing, place() seems easy because you just have to give it coordinate and it would place widgets right there. I know that its tough but I really wanna see how to do it.

import tkinter as tk

root = tk.Tk()

button = tk.Button(root, text="Hello")
button.place(x=50, y=50)

root.mainloop()
  • You can use "relheight" and "relwidth" parameters of the place method. As well you can use "relx" and "rely" to make coordinates of the button to also depend on the container sizes. Each of these parameters take values between 0 and 1. Read more about place method [there](https://www.tcl.tk/man/tcl8.7/TkCmd/place.html) – Danya K Aug 20 '23 at 17:57

1 Answers1

0

place is the wrong tool for the job if you're trying to create a complex responsive UI. Both pack and grid are much easier because they do all of the work of resizing for you.

That being said, if you insist on using place and you want the widgets to resize with the window, you need to use relative placement and/or relative sizes.

place supports the following keyword arguments:

  • relx, rely represents relative x,y coordinates, where 0 represents the left edge and 1.0 represents the right edge. The values .5,.5 represent the center of the containing widget.

  • relwidth, relheight represents the relative width or height of a widget compared to its container. For example, to make a label be the full width of the window it is in you can use a relwidth of 1.0. A relwidth of .5 would make it half as wide, etc.

  • x, y represent absolute positions, or an additional number of pixels added to or subtracted from the relative coordinates. For example, relx=.5, x=5 means five pixels to the right of the middle of the containing widget.

  • width, height represent an absolute width or height.

  • anchor defines what part of the widget should appear at the given coordinate.

For example, if you wanted to place a frame at the top of the window and have it extend the full width of the window, you might specify it like so:

frame.place(x=0, y=0, anchor="nw", relwidth=1.0)

If you wanted a button placed in the bottom-right of a widget, with a margin of 10 pixels to the right and below, you might do it like this:

button.place(relx=1.0, x=-10, rely=1.0, y=-10, anchor="se")

Here is an example with those two examples in a window. Notice how they keep their position when you manually resize the window.

import tkinter as tk

root = tk.Tk()
root.geometry("200x100")

frame = tk.Frame(root, background="black", height=50)
button = tk.Button(root, text="Ok")

frame.place(x=0, y=0, anchor="nw", relwidth=1.0)
button.place(relx=1.0, x=-10, rely=1.0, y=-10, anchor="se")

tk.mainloop()

screenshot - small

screenshot - large

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685