0
votes

I am writing a program which displays a grid of widgets. When the window resizes horizontally,the widgets resize, but when the window resizes vertically, I want the height of the widgets to remain the same, but the number of rows to change. I had no luck with frame.bind("", configure), the window won't resize. root.after(1000, rsz) works, but if I make the delay much smaller, it does not. It just seems there should be a better way to do this. Any suggestions?

import tkinter as tk
from tkinter import ttk
#def configure(event):
#    if not event.widget.master.master:
#        rsz()
root=tk.Tk()
root.geometry("500x500")
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)
def rsz():
    global lasth
    h = root.winfo_height()
    if h != lasth:
        for widget in frame.winfo_children():
            widget.destroy()
        for row in range(int((h)/26)):
            frame.grid_rowconfigure(row, weight=0)
            for col in range(6):
                frame.grid_columnconfigure(col, weight=1)
                ttk.Button(frame, text='row{}, col{}'.format(row,col)).grid(row=row, column=col, sticky='EWNS')
        lasth = h
    root.after(1000, rsz)
frame=tk.Frame(root,padx=5,pady=5)
frame.grid(row=0,column=0, sticky="NSEW")
lasth = -1
rsz()
#frame.bind("<Configure>", configure)
root.mainloop()
1
When i run your code the initial window loads with 18rows / 5 cols. When i use the maximise window button it loads 38rows / col count remains the same..is that what your after?? Im not sure I totally understand your issue - James Cook
That is the behavior I want. Resizing the window by dragging the bottom bar works with the occasional glitch. If you change the delay in the root.after to 100, it doesn't work at all. I would like something that always works without problem. - user2801282

1 Answers

0
votes

rsz() should work fine with frame.bind('<Configure>'):

import tkinter as tk
from tkinter import ttk

root=tk.Tk()
root.geometry("500x500")
root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)

lasth = -1

def rsz(event):
    global lasth
    #h = root.winfo_height()
    h = event.height
    if h != lasth:
        for widget in frame.winfo_children():
            widget.destroy()
        for row in range(h//26):
            frame.grid_rowconfigure(row, weight=1)
            for col in range(6):
                ttk.Button(frame, text='row{}, col{}'.format(row,col)).grid(row=row, column=col, sticky='nsew')
        lasth = h

frame=tk.Frame(root, padx=5, pady=5)
frame.grid(row=0, column=0, sticky="nsew")
# since number of columns does not change
# grid_columnconfigure() can be called once for each column
for col in range(6):
    frame.grid_columnconfigure(col, weight=1)
frame.bind("<Configure>", rsz)

root.mainloop()