Home > Mobile >  Tkinter window resize to fit content without touching
Tkinter window resize to fit content without touching

Time:05-01

I have created an application that required to use the place() manager. I tried using pack() and grid() but after many tries and lots of effort it did not work for my goals. Since I use relx= and rely= almost all the time and I want to put my app on multiple OS's I need to have the window resize to fit all the widgets without them touching.

Is there a way to do this? Since many OS's and their updates change rendering the sizes of widgets changes greatly and I don't want the user to have to resize the window all the time. I want it to just fit as tightly as possible or get the minimum width and height to I can add some buffers. Is this possible? If not, is there a way to fix my app without having to rewrite everything?

Note:

I found something similar: Get tkinter widget size in pixels, but I couldn't properly get it to work.

CodePudding user response:

I figured it out. You can use the widget.winfo_height()/widget.winfo_width() functions to get the minimum pixel sizes. Since the window.geometry() function requires pixel sizes you can make two lists: one for width, and one for height. By adding the minimum amount of widgets you can get the desired size.

Code:

height_widget_list = [main_label, main_notebook, the_terminal, quit_button, settings_button]
width_height_list = [commands_label, main_notebook, quit_button]
widget_list = [main_label, main_notebook, the_terminal, quit_button, settings_button, commands_label]
# Widgets must be updated for height and width to be taken
for widget in widget_list:
    widget.update()
height_required_list = []
width_required_list = []
# Collects data
for widget in height_widget_list:
    height_required_list.append(int(widget.winfo_height()))
for widget in width_height_list:
    width_required_list.append(int(widget.winfo_width()))
# Get height requirement
minimum_height = 0
for height in height_required_list:
    minimum_height  = height
# Get width requirement
minimum_width = 0
for width in width_required_list:
    minimum_width  = width
# Make window correct size make window require the correct sizing
window.geometry("{}x{}".format(minimum_width, minimum_height))
window.resizable(False, False)
  • Related