Search code examples
tkinter

I want to have a scrollbar on a text area in Tkinter, but not sure what's wrong with the following codes:


            self.myfrm=Frame(nb, name=self.wzsgclass)
            self.myfrm.pack()
            self.sbtn = Button(self.myfrm, text='Update', underline=0,
                    command=self.update)
            self.sbtn.pack(anchor=NW, padx=7, pady=5)
            #self.txtarea=Label(self.myfrm, justify=LEFT, ancticky=W, pady=or=N, text=self.rslt)
            self.txtarea=Text(self.myfrm, width=800, height=600)
            self.txtarea.pack()
            self.txtarea.insert('3.0',self.rslt)
            self.txtarea.bind("<Key>", lambda e: "break")
            self.vscroll = Scrollbar(self.myfrm, orient=VERTICAL, command=self.txtarea.yview)
            self.txtarea['yscroll'] = self.vscroll.set
            self.vscroll.pack(side='right', fill='y')

I can see the button and the text area, but no scrollbar. Thanks in advance for any help.


Solution

  • pack works by placing objects in the available remaining space. When you do self.txtarea.pack() without arguments it is the same as self.txtarea.pack(side="top"). Any other widgets you pack will be below this widget.

    Because you packed the text widget first, it used up all of the remaining space. If there was any visible space remaining, it would be below the text widget. If your window is of a fixed size, there may not have been any free visible space after packing the text widget. If the window was large enough, you would have seen the scrollbar below the text widget.

    The order that you pack widgets matters, since each widget that is packed removes some amount of space, and any subsequent calls can only affect the remaining space. If you try to pack widgets that are too big for the space (eg: if you have a fixed window size), pack will start reducing windows to their smallest size before finally clipping the widget entirely. It does this in the reverse order that the widgets were packed. Since the scrollbar was last to be packed, it is the first to get removed if there's no room.

    For a definitive description of the packer algorithm, see The Packer Algorithm in the official tcl/tk documentation.