Home > Enterprise >  Tkinter - How to dynamically resize gradient frames?
Tkinter - How to dynamically resize gradient frames?

Time:10-11

I would like to know how I can resize automatically the following gradient frames based on the window size.

from tkinter import *

class InventorySystem:
    def __init__(self, root):
        self.root = root
        self.root.title("Inventory System")
        self.root.geometry("1366x768")

        j = 0
        colors = ["#007F5F", "#2B9348", "#55A630", "#80B918", "#AACC00", "#BFD200",
                  "#D4D700", "#DDDF00", "#EEEF20", "#FFFF3F"]
        for color in colors:
            Frame(self.root, width = 1366 / len(colors), height = 768,
                  bg = color).place(x = j, y = 0)
            j = j   1366 / len(colors)

if __name__ == "__main__":
    root = Tk()
    application = InventorySystem(root)
    root.mainloop()

CodePudding user response:

What you want to do is somewhat complex, so might be challenging even if you weren't just learning how to use tkinter (only exacerbated by the fact it's so poorly documented). So I've create an example of how to do it based on the code in your question.

One non-intuitive thing (to me) is that the Event handling "callback" function for the <'Configure>' event of a window gets called for the window itself and for all the widgets inside it — which can be very confusing if you don't realize that's what happens.

I've also changed and reformatted your code to more closely follow the screenshot showing window being resized

CodePudding user response:

You can use relative options of .place():

# relative width of each frame
# 1.0 means same width of parent
relw = 1 / len(colors) 
for j, color in enumerate(colors):
    Frame(self.root, bg=color).place(relx=j*relw, y=0, relwidth=relw, relheight=1)

Refer to official document on place() for details.

  • Related