I’m trying to attach a scrollbar to a list box in Tkinter, but whenever the code reaches one of the .pack() lines it freezes… any idea why? (I’ve experimented with running an example code that does the same thing that I found on the internet and that worked fine).
#Read Box
self.scrollbar = Tkinter.Scrollbar(self.frame)
#self.scrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
self.read = Tkinter.Listbox(self.frame, width=50, yscrollcommand=self.scrollbar.set)
self.read.grid(row=1,column=2)
#self.read.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH)
self.scrollbar.config(command=self.read.yview)
Any idea why this code does not work?
Updated code:
#Read Box
self.scrollbar = Tkinter.Scrollbar(self.frame)
self.scrollbar2.grid(sticky=Tkinter.N+Tkinter.S) #row=1, column=2 side=Tkinter.RIGHT, fill=Tkinter.Y
self.read = Tkinter.Listbox(self.frame, width=50, yscrollcommand=self.scrollbar.set)
self.read.grid(row=1,column=2) #side=Tkinter.LEFT, fill=Tkinter.BOTH
self.scrollbar.config(command=self.read.yview)
Alright that was a minor mistake (I confused scrollbar and scrollbar2). Anyway now I have this code:
#Read Box
self.scrollbar = Tkinter.Scrollbar(self.frame)
self.scrollbar.grid(row=1, column=2)
self.read = Tkinter.Listbox(self.frame, width=50, yscrollcommand=self.scrollbar.set)
self.read.grid(row=1,column=2)
self.scrollbar.config(command=self.read.yview)
This does not freeze and the scrollbar appears, but they are not connected to (or have any control over) the listbox. With regard to the rest of the code, it is all grid statements, no pack.
I found the problem, the scrollbar was missing sticky=Tkinter.N+Tkinter.S. Here’s the finished code (with added horizontal bars).
#Read Box
self.scrollbar = Tkinter.Scrollbar(self.frame)
self.scrollbar.grid(row=1, column=3, sticky=Tkinter.N+Tkinter.S)
self.hbar = Tkinter.Scrollbar(self.frame, orient=Tkinter.HORIZONTAL)
self.hbar.grid(row=2, column=2, sticky=Tkinter.E+Tkinter.W)
self.read = Tkinter.Listbox(self.frame, width=50, yscrollcommand=self.scrollbar.set, xscrollcommand=self.hbar.set)
self.read.grid(row=1,column=2)
self.scrollbar.config(command=self.read.yview)
self.hbar.config(command=self.read.xview)
Seems that you’re mixing
packandgridat same level (i.e. not inside two separateFrameor else). This will make your app to freeze, as described in documentation.So what you should do is to
.gridyour scrollbar 🙂More material: as said above, you can mix different window managers, but not inside the same frame. What is below is legal and will work: