How to add xscrollbar to text widget in tkinter

According to this source: both x and y scrollbars can be added to a tkinter Text () widget. The codes that work in the procedural method are:

from tkinter import *
root = Tk()

frame = Frame(master, bd=2, relief=SUNKEN)

frame.grid_rowconfigure(0, weight=1)
frame.grid_columnconfigure(0, weight=1)

xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
xscrollbar.grid(row=1, column=0, sticky=E+W)

yscrollbar = Scrollbar(frame)
yscrollbar.grid(row=0, column=1, sticky=N+S)

text = Text(frame, wrap=NONE, bd=0,
        xscrollcommand=xscrollbar.set,
        yscrollcommand=yscrollbar.set)

text.grid(row=0, column=0, sticky=N+S+E+W)

xscrollbar.config(command=text.xview)
yscrollbar.config(command=text.yview)

frame.pack()
root.mainloop()

      

However, I choose a class method and write the codes below, according to the codes below. scrollbar works, but x scrollbar doesn't work. Why isn't scrolling working in this example?

import tkinter as tk


 class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.x_scrollbar = tk.Scrollbar(master=self, orient="horizontal")
        self.x_scrollbar.grid(row=1, column=0, sticky="w, e")

        self.y_scrollbar = tk.Scrollbar(master=self)
        self.y_scrollbar.grid(row=0, column=1, sticky="n, s")

        self.text = tk.Text(master=self, width=100, height=25, bg="black", fg="white", wrap=None)
        self.text.grid(row=0, column=0, sticky="n, s, e, w")

        self.configure_widgets()
        self.pack()

    def configure_widgets(self):
        self.text.configure(xscrollcommand=self.x_scrollbar.set, yscrollcommand=self.y_scrollbar.set)
        self.x_scrollbar.config(command=self.text.xview)
        self.y_scrollbar.config(command=self.text.yview)

if __name__ == "__main__":
    root = tk.Tk()
    app = App(master=root)
    app.mainloop()

      

+3


source to share


1 answer


The problem here is not the scrollbar code, but the assignment None

in the wrapper configuration of your textarea.

Change

wrap=None

      

To

wrap='none'

      



on an unrelated note

change sticky="n, s, e, w"

to sticky="nsew"

, commas mean nothing in the quote here. And your other sheets should be "we"

and"ns"

You may have tried the tkinter CONSTANTS version of the stick. It will look like this: sticky=(N, S, E, W)

. However, since you didn't import it *

, this won't work. You can import each constant from tkinter separately, but in this case it is better to use sticky="nsew"

.

For reference only, is the list of constants 'nsew'

you get when importing *

fromtkinter

N='n'
S='s'
W='w'
E='e'
NW='nw'
SW='sw'
NE='ne'
SE='se'
NS='ns'
EW='ew'
NSEW='nsew'

      

+5


source







All Articles