Reputation: 53
I've already checked this question out but it doesn't answer my question
I have the following code:
from tkinter import *
root = Tk()
root.geometry("800x600")
Scr = Scrollbar(root)
Scr.pack(side = RIGHT,fill =Y)
cnvs = Canvas(root,width = 800,height = 560,yscrollcommand = Scr.set)
cnvs.place(x=0,y=40)
for i in range(100):
x = Label(cnvs,text=f"This is label {i}")
x.pack()
Scr.config(command = cnvs.yview)
root.mainloop()
When I run this, the scrollbar doesn't work and remains inactive throughout.
What am I doing wrong?
Upvotes: 0
Views: 83
Reputation: 7176
There are a couple of things:
When you want to scroll widgets placed on a canvas you should use canvas methods such as create_text()
and not pack()
or grid()
them, otherwise they will not scroll.
Then you have to provide the canvas a scrolling region. Put objects on canvas FIRST, then define scrollregion.
from tkinter import *
root = Tk()
root.geometry('300x200+800+50')
mainframe = Frame(root)
mainframe.pack(pady=10, padx=10, expand='yes', fill='both')
# Making sure only canvas will change with window size
mainframe.grid_columnconfigure(0, weight=1)
mainframe.grid_rowconfigure(0, weight=1)
scr = Scrollbar(mainframe, orient='vertical')
scr.grid(column=1, row=0, sticky='ns')
canvas = Canvas(mainframe, bg='khaki', yscrollcommand=scr.set)
canvas.grid(column=0, row=0, sticky='ewns')
scr.config(command=canvas.yview)
for i in range(100):
# Create canvas objects at canvas positions
canvas.create_text(0, 20*i, text=f"This is label {i}", anchor='w')
# Create objects and pack them, will NOT scroll
x = Label(canvas,text=f"Will not scroll {i}")
x.pack()
# Define scrollregion AFTER widgets are placed on canvas
canvas.config(scrollregion=canvas.bbox('all'))
root.mainloop()
Upvotes: 2