Search code examples
pythontkinter

Tkinter not updating frame after configurating height


I have some frames set up. The first is self.MainFrame, and takes up the entire window. The second one is self.testFrame inside self.MainFrame, with an initiall height of 500, and sticky to the sides. Everything set up with the grid manager.

I also have a button, inside self.testFrame, with grid propagation off. And when I press it, the height of self.testFrame should change to 100. However, when I press it, nothing happens. It only changes when i resize the window. (video showcase: https://www.youtube.com/watch?v=fwPpn1Bw7o4) I cannot understand what is happening.

This is the code:

from tkinter import Tk, Button, Frame

class Mygui():
    def __init__(self) -> None:
        self.root = Tk()
        self.root.geometry("800x800")
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        self.MainFrame = Frame(self.root, bg= "red")
        self.MainFrame.grid(row=0, column=0, sticky="NSEW")
        self.MainFrame.columnconfigure(0, weight=1)

        self.testFrame = Frame(self.MainFrame, bg= "yellow", height=500)
        self.testFrame.grid(row=0, column=0, sticky="EW")
        self.testFrame.grid_propagate(False)

        self.button = Button(self.testFrame, command=self.test, text="Test me!")
        self.button.grid(row=1, column=0)
    
    def test(self):
        self.testFrame.configure(height=100)
        print("a")

A = Mygui().root.mainloop()

EDIT: i forgot to say that i have also tried the following

def test(self):
    self.testFrame.configure(height=100)
    self.root.update()
    print("a")

Solution

  • I have no explanation as to why your code didn't work but with a few small changes it now seems to work as intended. All changes are commented.

    from tkinter import Tk, Button, Frame
    
    class Mygui():
        def __init__(self) -> None:
            self.root = Tk()
            # Removed self.root.geometry("800x800")
            self.root.columnconfigure(0, weight=1)
            self.root.rowconfigure(0, weight=1)
    
            self.MainFrame = Frame(self.root, bg= "red")
            self.MainFrame.grid(row=0, column=0, sticky="NSEW")
            self.MainFrame.columnconfigure(0, weight=1)
    
            # included width and height
            self.testFrame = Frame(self.MainFrame, bg= "yellow", width = 800, height=700)
            self.testFrame.grid(row=0, column=0, sticky="EW")
            self.testFrame.grid_propagate(False)
    
            self.button = Button(self.testFrame, command=self.test, text="Test me!")
            self.button.grid(row=1, column=0)
        
        def test(self):
            self.testFrame.configure(height=100)
            # make sure MainFrame is still visible
            self.root.geometry("800x700")
    
    A = Mygui()
    A.root.mainloop()