Home > Enterprise >  How do I change this code to add a horizontal scrollbar to a Frame? (tkinter)
How do I change this code to add a horizontal scrollbar to a Frame? (tkinter)

Time:01-18

I am trying to implement a scrollbar to a Frame object I have, so if there are too many widgets inside it, I can scroll down to see more of them. I found this code and copied it into my program to use:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
container = ttk.Frame(root)
canvas = tk.Canvas(container)
scrollbar = ttk.Scrollbar(container, orient="vertical", command=canvas.yview)
scrollable_frame = ttk.Frame(canvas)

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

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

canvas.configure(yscrollcommand=scrollbar.set)

for i in range(50):
    ttk.Label(scrollable_frame, text="Sample scrolling label").pack()

container.pack()
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

root.mainloop()

It works, but I changed the code to add a horizontal scrollbar as well. I tried adding the same code with some changes that I thought would make it work, like this:

super().__init__(container, *args, **kwargs)
        canvas = Canvas(self, width=1000, height=700)
        yscrollbar = ttk.Scrollbar(self, orient="vertical", command=canvas.yview)
        xscrollbar = ttk.Scrollbar(self, orient="horizontal", command=canvas.xview)
        self.scrollable_frame = ttk.Frame(canvas)

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

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

        canvas.configure(yscrollcommand=yscrollbar.set)
        canvas.configure(xscrollcommand=xscrollbar.set)

        canvas.pack(side="left", fill="both", expand=True)
        yscrollbar.pack(side="right", fill="y")
        xscrollbar.pack(side="left", fill="x")

However, it didn't work like I expected, but instead added a tiny scrollbar to the side that doesn't do anything: [![enter image description here][1]][1]

How should've I changed the code to make a working horizontal scrollbar? [1]: https://i.stack.imgur.com/xp1ju.png

CodePudding user response:

The order of packing those widgets matters and also side="bottom" should be used instead for xscrollbar:

xscrollbar.pack(side="bottom", fill="x")
canvas.pack(side="left", fill="both", expand=True)
yscrollbar.pack(side="right", fill="y")
  •  Tags:  
  • Related