滚动条未拉伸以适合文本小部件

时间:2013-05-16 01:42:28

标签: python tkinter widget scrollbar

我能够让Scrollbar使用Text窗口小部件,但由于某种原因,它不适合文本框。

有没有人知道有什么方法可以改变滚动条小部件的高度或类似的东西?

txt = Text(frame, height=15, width=55)
scr = Scrollbar(frame)
scr.config(command=txt.yview)
txt.config(yscrollcommand=scr.set)
txt.pack(side=LEFT)

3 个答案:

答案 0 :(得分:8)

在您的问题中,您正在使用packpack可以选择告诉它在x轴和y轴中的一个或两个上增长或缩小。垂直滚动条通常应在y轴上增大/缩小,而在x轴上应为水平滚动条。文本小部件通常应该填充两个方向。

要在框架中执行文本小部件和滚动条,通常会执行以下操作:

scr.pack(side="right", fill="y", expand=False)
text.pack(side="left", fill="both", expand=True)

以上说明了以下内容:

  • 滚动条位于右侧(side="right"
  • 滚动条应拉伸以填充y轴(fill="y"
  • 中的任何额外空格
  • 文本小部件位于左侧(side="left"
  • 文本小部件应拉伸以填充x和y轴上的任何额外空间(fill="both"
  • 文本窗口小部件将展开以占用包含框架中的所有剩余空间(expand=True

有关详细信息,请参阅http://effbot.org/tkinterbook/pack.htm

答案 1 :(得分:4)

以下是一个例子:

from Tkinter import *
root = Tk()
text = Text(root)
text.grid()
scrl = Scrollbar(root, command=text.yview)
text.config(yscrollcommand=scrl.set)
scrl.grid(row=0, column=1, sticky='ns')
root.mainloop()

这会生成一个文本框,而sticky='ns'会使滚动条一直向上和向下移动

答案 2 :(得分:4)

使用带有集成滚动条的文本框的简单解决方案:

Python 3

#Python 3
import tkinter 
import tkinter.scrolledtext

tk = tkinter.Tk() 
text = tkinter.scrolledtext.ScrolledText(tk)
text.pack()
tk.mainloop()

阅读文本框:

string = text.get("1.0","end")   # reads from the beginning to the end

当然,如果需要,您可以缩短进口。

Python 2 中改为import ScrolledText

相关问题