简体   繁体   English

滚动条使用tkinter和Python出现在错误的位置

[英]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: 我正在用Python在tkinter上做一个教程,当前步骤是编写以下代码:

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. 我已经在Python 2.7和Python 3.5中尝试了相同的结果。 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: 如果要使用pack而不是grid ,则希望框架将列表框和滚动条都打包在其中,如下所示:

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. pack使用“盒子”的隐喻。 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. 打包列表框时,您没有指定面,所以tkinter将其放在顶部。 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. Tkinter是tcl / tk的包装。 The definitive definition of how pack works is on the tcl/tk man pages: 在tcl / tk手册页上有关于pack工作原理的明确定义:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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