简体   繁体   中英

Scrollbar appearing in the wrong spot using tkinter and Python

I'm doing a tutorial on tkinter in Python, and the current step is to write this code:

from tkinter import *
win=Tk()

lb = Listbox(win,height=3)
lb.pack()
lb.insert(END,"first entry")
lb.insert(END,"second entry")
lb.insert(END,"third entry")
lb.insert(END,"fourth entry")

sb=Scrollbar(win,orient=VERTICAL)
sb.pack(side=LEFT,fill=Y)

Apparently this is supposed to pack the scrollbar next to the list box, but instead it places it UNDER the listbox. I've tried this in both Python 2.7 and Python 3.5 with the same results. What am I doing wrong?

If you want to use pack instead of grid , you want a frame to pack both the listbox and the scrollbar in, like this:

fr = Frame(win)
lb = Listbox(fr, height=3)
lb.pack(side=LEFT, fill='both')
lb.insert(END, "first entry")
lb.insert(END, "second entry")
lb.insert(END, "third entry")
lb.insert(END, "fourth entry")
sb=Scrollbar(fr, orient=VERTICAL)
sb.pack(side=LEFT, fill=Y)
fr.grid()

Or you could grid them like this:

lb = Listbox(win, height=3)
lb.grid(row=0, column=0, sticky=(N, W, E, S))
lb.insert(END, "first entry")
lb.insert(END, "second entry")
lb.insert(END, "third entry")
lb.insert(END, "fourth entry")
sb=Scrollbar(win, orient=VERTICAL)
sb.grid(row=0, column=1, sticky=(N, S))

pack uses a "box" metaphor. Each object is placed against one side of the space available in the box. If you don't specify a side, the default is "top".

When you packed the listbox you didn't specify a side so tkinter placed it at the top. Imagine the box has not been cut in half: the top half has the listbox and the bottom half is empty.

When you pack the scrollbar on the left, it goes on the left of the empty portion of the box , which is why it appears below the listbox.

You can solve this problem by placing the listbox on the left or right, and then placing the scrollbar on the left or right.

Tkinter is a wrapper around tcl/tk. The definitive definition of how pack works is on the tcl/tk man pages:

https://www.tcl.tk/man/tcl/TkCmd/pack.htm#M26

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM