我正在尝试将滚动条附加到我的文本字段,但未能成功。这是代码段:
self.scroller = Scrollbar(self.root)
self.scroller.place(x=706, y=121)
self.outputArea = Text(self.root, height=26, width=100)
self.outputArea.place(x=0, y=120)
self.scroller.config(command=self.outputArea.yview)
self.outputArea.config(state=DISABLED, yscrollcommand = self.scroller.set)
此代码在我的文本字段旁边放置了一个非常小的滚动条(非常小,我的意思是您可以看到向上和向下箭头,但中间没有任何东西)。当我的文本字段填满时,我可以滚动它,但是有没有办法至少设置滚动条的高度,使其看起来与文本字段的高度相同?
最佳答案
Tkinter有三个几何管理器:pack , grid , 和 place .
通常建议使用 Pack 和 Grid。
您可以使用 grid manager's 行和列选项
将 Scrollbar 放置在 Text 小部件旁边。
将 Scrollbar 小部件的 command 选项设置为文本的 yview 方法。
scrollb = tkinter.Scrollbar(..., command=txt.yview)
将 Text 小部件的 yscrollcommand 选项设置为滚动条的 set 方法。
txt['yscrollcommand'] = scrollb.set
这是一个使用 ttk 的工作示例:
import tkinter
import tkinter.ttk as ttk
class TextScrollCombo(ttk.Frame):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# ensure a consistent GUI size
self.grid_propagate(False)
# implement stretchability
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
# create a Text widget
self.txt = tkinter.Text(self)
self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)
# create a Scrollbar and associate it with txt
scrollb = ttk.Scrollbar(self, command=self.txt.yview)
scrollb.grid(row=0, column=1, sticky='nsew')
self.txt['yscrollcommand'] = scrollb.set
main_window = tkinter.Tk()
combo = TextScrollCombo(main_window)
combo.pack(fill="both", expand=True)
combo.config(width=600, height=600)
combo.txt.config(font=("consolas", 12), undo=True, wrap='word')
combo.txt.config(borderwidth=3, relief="sunken")
style = ttk.Style()
style.theme_use('clam')
main_window.mainloop()
Scrollbar 变小的部分是sticky='nsew'
,
您可以阅读 → here .
现在对您有帮助的是,不同的 Tkinter 小部件可以在同一程序中使用不同的几何管理器,只要它们这样做不共享相同的父级。
tkinter.scrolledtext模块包含一个名为 ScrolledText 的类,它是一个复合小部件(文本和滚动条)。
import tkinter
import tkinter.scrolledtext as scrolledtext
main_window = tkinter.Tk()
txt = scrolledtext.ScrolledText(main_window, undo=True)
txt['font'] = ('consolas', '12')
txt.pack(expand=True, fill='both')
main_window.mainloop()
这是implemented的方式值得一看。
关于python - 如何将滚动条附加到文本小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13832720/