我在 Tkinter 的文本小部件内的滚动条中设置有问题。我知道,最好使用网格来定位小部件,但我想将我的小部件设置在具有指定高度和宽度的绝对位置(x,y - GUI 图片上的红点)。
我的代码:
from Tkinter import *
from ttk import *
class NotebookDemo(Frame):
def __init__(self):
Frame.__init__(self)
self.pack(expand=1, fill=BOTH)
self.master.title('Sample')
self.master.geometry("650x550+100+50")
self._initUI()
def _initUI(self):
self._createPanel()
def _createPanel(self):
# create frame inside top level frame
panel = Frame(self)
panel.pack(side=TOP, fill=BOTH, expand=1)
# create the notebook
nb = Notebook(panel)
nb.pack(fill=BOTH, expand=1, padx=2, pady=3)
self._FirstTab(nb)
def _FirstTab(self, nb):
# frame to hold content
frame = Frame(nb)
#textbox
txtOutput = Text(frame, wrap = NONE, height = 17, width = 70)
txtOutput.place(x=10, y=75)
#button
btnStart = Button(frame, text = 'Start', underline=0)
btnStart.place(x=220, y=380)
#scrollbar
#vscroll = Scrollbar(frame, orient=VERTICAL, command=txtOutput.yview)
#txtOutput['yscroll'] = vscroll.set
#vscroll.pack(side=RIGHT, fill=Y)
#txtOutput.pack(fill=BOTH, expand=Y)
#add to notebook (underline = index for short-cut character)
nb.add(frame, text='TAB 1', underline=0, padding=2)
if __name__ == '__main__':
app = NotebookDemo()
app.mainloop()
如果我取消注释这部分代码(设置滚动条):
vscroll = Scrollbar(frame, orient=VERTICAL, command=txtOutput.yview)
txtOutput['yscroll'] = vscroll.set
vscroll.pack(side=RIGHT, fill=Y)
我的滚动条位于所有窗口内,而不是文本框内:
但是我当然希望在文本框小部件(黑色边框)内有滚动条。 如果我对文本框使用 pack 函数:
txtOutput.pack(fill=BOTH, expand=Y)
文本小部件填充整个窗口...:
我真的不知道如何解决这个问题。 任何帮助将不胜感激。 谢谢!
编辑:
当然我也可以在 Scrollbar 上使用 place 方法,但是我不能改变它们的长度,因为它没有属性长度。
vscroll.place(x=573, y=75)
最佳答案
虽然我很少推荐 place
,但是当您利用配置选项时它会非常强大。例如,您可以使用 in_
指定一个小部件,该小部件将相对于该小部件放置。您可以使用 relx
指定相对的 x 坐标,也可以使用 relheight
指定高度。
在你的情况下,你可以尝试这样的事情:
vscroll.place(in_=txtOutput, relx=1.0, relheight=1.0, bordermode="outside")
如果你想要滚动条嵌入文本小部件内部的错觉,就像在某些平台上常见的(或曾经是)一样,我建议将文本小部件和滚动条放在一个框架中。你可以使用 pack
将小部件放入框架中,并继续使用 place
将组合放置在您想要的任何位置。
例如:
txtFrame = Frame(frame, borderwidth=1, relief="sunken")
txtOutput = Text(txtFrame, wrap = NONE, height = 17, width = 70, borderwidth=0)
vscroll = Scrollbar(txtFrame, orient=VERTICAL, command=txtOutput.yview)
txtOutput['yscroll'] = vscroll.set
vscroll.pack(side="right", fill="y")
txtOutput.pack(side="left", fill="both", expand=True)
txtFrame.place(x=10, y=75)
关于python - 文本小部件内 Tkinter 中的滚动条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41976546/