python - 如何将滚动条附加到文本小部件?

标签 python tkinter

我正在尝试将滚动条附加到我的文本字段,但未能成功。这是代码段:

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/

相关文章:

python - 返回大于 x 的数组值

python - 返回多个范围的 numpy 数组

Python:绘制非重叠圆圈 - 递归失败, 'while' 有效

Python:Tkinter 和乌龟

python - tkinter python 按钮在后台命令中运行

python - 在Python中对dict中的值进行分组和排序

python - 读取带有十六进制数据的文件并将其存储到Python中的列表中

python - 入场费根据年龄而定

python - 获取 Tkinter 文本小部件中最后一个字符的位置

python - Tkinter:在不触发回调的情况下设置 'scale' 值?