AppCreator
AppCreator

Reputation: 241

Why is the scrollbar not working in the canvas (tkinter)?

I want the window frame to expand the whole canvas AND have a scrollbar. Now the scrollbar is there visually but is not working as a scrollbar.

root = Tk()

def onCanvasConfigure(e):
    my_canvas.configure(scrollregion = my_canvas.bbox("all")) #make the scrollfunction work
    my_canvas.itemconfig('window', height=(my_canvas.winfo_height()-100), width=(my_canvas.winfo_width()-100)) #set the frame window to canvas size


#Below code to add scrollbar to app. 
# Layers (root -> main_frame -> my_canvas -> window (frame))

# Create A Main Frame
main_frame = Frame(root)
main_frame.pack(fill=BOTH, expand=1)

# Create A Canvas
my_canvas = Canvas(main_frame)
my_canvas.pack(side=LEFT, fill=BOTH, expand=1)

# Add A Scrollbar To The Canvas
my_scrollbar = ttk.Scrollbar(main_frame, orient=VERTICAL, command=my_canvas.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)

# Configure The Canvas
my_canvas.configure(yscrollcommand=my_scrollbar.set)


# Create ANOTHER Frame INSIDE the Canvas
window = Frame(my_canvas)

# Add that New frame To a Window In The Canvas
my_canvas.create_window((0,0), window=window, anchor="nw", tags="window")

my_canvas.bind("<Configure>", onCanvasConfigure)

See clip: https://jumpshare.com/v/TJlbWJac5d4rwp3DwnFw

Upvotes: 0

Views: 1143

Answers (1)

acw1668
acw1668

Reputation: 46669

Since you resize the internal frame window to the same size of canvas, so the scrollregion will be around the same as the size of the canvas which makes the scrollbar not activated.

If you set the height of the frame larger than that of canvas, the scrollbar will be activated:

def onCanvasConfigure(e):
    # resize the frame with double height of canvas
    my_canvas.itemconfig('window', height=e.height*2, width=e.width)
    # update scrollregion
    my_canvas.configure(scrollregion=my_canvas.bbox("all"))

Upvotes: 1

Related Questions