Home > OS >  How can I change the size of the buttons inside a frame with create_window?
How can I change the size of the buttons inside a frame with create_window?

Time:12-21

my problem is that I can't change the size of the buttons so that they fill the frame inside the "canvas". The buttons stay at a very small size, they only resize with the text that is entered or I could use width but I want to fill as if it were relwidth so I can resize easily

I've tried researching, but research just doesn't work. I put fill="x" in set_news to fill the width but it can't.

from tkinter import Frame, Label, Button, Entry, messagebox, ttk, Scrollbar, Canvas

import base64
import json


class WatchNewsFrame(Frame):
    name = "WatchNewsFrame"

    def __init__(self, parent, file):
        super().__init__()
        self.Parent = parent
        self.file = file
        self.initializecomponents()

    def set_news(self):
        data = json.load(open(self.file))["News"]
        for key in range(30):
            Panel = Button(self.frame, height=10)

            Panel.config(bg="#656565", activebackground="#808080")
            Panel.pack(fill="x")
        pass


    def initializecomponents(self):
        Frame.__init__(self, self.Parent)
        self.canvas = Canvas(self)
        self.Scrollbar = ttk.Scrollbar(self, orient="vertical")
        self.frame = Frame(self.canvas)

        # this frame
        self.config(background=self.Parent["background"])
        self.place(relwidth=0.95, relheight=0.95, relx=0.5, rely=0.5, anchor="center")

        # ItemsScrooll
        self.Scrollbar.config(orient="vertical", command=self.canvas.yview)
        self.Scrollbar.place(relheight=.85, relwidth=.015, relx=.95, rely=.5, anchor="center")

        # itemsFrame
        self.canvas.config(bg="#606060", highlightbackground="#FFFFFF", yscrollcommand=self.Scrollbar.set)
        self.canvas.create_window(2, 0, window=self.frame, anchor="nw",)
        self.canvas.place(relheight=0.85, relwidth=0.9, relx=0.5, rely=0.5, anchor="center")
        self.canvas.bind('<Configure>', lambda e: self.canvas.config(scrollregion=self.canvas.bbox("all")))

        # events
        self.set_news()
        pass
    pass




CodePudding user response:

Since you have used fill="x" on those buttons, you just need to set the width of the frame the same as the canvas when the canvas is resized, then the width of those buttons will be changed as well.

...
# save the item ID of the frame
self.frame_id = self.canvas.create_window(2, 0, window=self.frame, anchor="nw")
...
# set width of the frame same as the canvas
self.canvas.bind('<Configure>', lambda e: self.canvas.itemconfigure(self.frame_id, width=e.width))
# update scrollregion when the frame is resized
self.frame.bind('<Configure>', lambda e: self.canvas.config(scrollregion=self.canvas.bbox("all")))
...
  • Related