Home > Software design >  Python Tkinter Scrollbar isn't displayed and doesn't work
Python Tkinter Scrollbar isn't displayed and doesn't work

Time:08-25

I tried to add a Scrollbar widget to my python Tkinter app. The problem is that it is not displayed and when I want to add some widget to the frame in which is placed the scrollbar those widgets are hidden. Here's my code:

import tkinter as tk
from tkinter import ttk
from tkinter import *

window = tk.Tk()
container = ttk.Frame(window)
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)

label_width = [26, 7, 10, 10, 10, 13, 19, 9, 7, 19, 10, 9, 10, 13, 10, 21, 9, 22]   
x_location = [0, 210, 269, 353, 437, 521, 629, 785, 861, 921, 1075, 1159,1230, 1313, 1420, 1503, 1670, 1740]
data = [["Stefan", "20", "2001"], ["Andrew", "15", "2006"], ["John", "10", "2003"]]
results = [[data[j][i] for j in range(len(data))] for i in range(len(data[0]))]

y = 0
for result in results:
    x = 0
    for i in result:
        share_detail = Label(scrollable_frame, text=i, anchor="center", borderwidth=2, relief="solid", width=label_width[x], font=("Calibri", 11))
        share_detail.place(x=x_location[x], y=22 * (y   1))
        x  = 1
    y  = 1
container.pack()
canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

window.mainloop()

The variable "results" is 2d array of string, in case is helping anyhow. So what's wrong with the code?

CodePudding user response:

Your code won't run as posted. However, one obvious problem is that you are configuring the scrollregion whenever the <Configure> event is fired on the frame, but you're using place which won't cause that event to be triggered.

This trick to reconfigure scrollregion only works when the frame resizes and place doesn't cause a parent widget -- in this case, scrollable_frame -- to grow or shrink. You'll need to use pack or grid on the labels, or explicitly resize the frame.

  • Related