0

I was trying to learn how to make frame scrollable. Now i got another problem how to center all the widgets horizontally in that frame. The labels, the buttons all appear on the left. How can I center them horizontally.

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

container = tk.Frame(root)
container.pack(fill="both", expand=True)

canvas = tk.Canvas(container)
canvas.pack(side="left", fill="both", expand=True)

scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
scrollbar.pack(side="right", fill="y")

canvas.configure(yscrollcommand=scrollbar.set)

scrollable_frame = ttk.Frame(canvas)
canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")

scrollable_frame.bind(
    "<Configure>",
    lambda e: canvas.configure(
        scrollregion=canvas.bbox("all")
    )
)

for i in range(50):
    tk.Label(scrollable_frame, text="Sample text").grid(row=i, column=0)
    tk.Button(scrollable_frame, text="Sample text").grid(row=i, column=1)

root.mainloop()
osman
  • 33
  • 7

2 Answers2

0

I think that you can find your answer here: How to horizontally center a widget using grid()?

In short, your labels and buttons are on the left-hand side of your frame because of the coordinates you gave to your scrollable_frame (0,0) Try to modify them for (100, 0) and you will see everything moving to the right. Then you can use variables to center the frame if you know the width of your frame.

This is my first reply on stackoverflow, I hope it is not too messy!

  • thank you I had tried that way but I want them to stay center whether the page full screen or not – osman Jan 26 '21 at 10:36
0

You can calculate the required position of the top-left corner of scrollable_frame and move the frame using canvas.coords() whenever the canvas is resized:

frame_id = canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")

def on_canvas_resize(event):
    x = (event.width - scrollable_frame.winfo_width()) / 2
    canvas.coords(frame_id, (x, 0))
    bbox = (0, 0, event.width, scrollable_frame.winfo_height())
    canvas.config(scrollregion=bbox)

canvas.bind("<Configure>", on_canvas_resize)
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • thank you it is ok for the first time maximizing window fullscreen but then if i press again to make smaller or hold window from the corners to change its size it does not work properly, – osman Jan 26 '21 at 11:52
  • It is caused by the `scrollregion`. Answer updated to configure the `scrollregion` properly. – acw1668 Jan 26 '21 at 12:35