According to this source: both x and y scrollbars can be added to the Text() widget of tkinter. The codes which work in 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 the class method and wrote the below codes, according to the below codes y scrollbar works but x scrollbar doesn't work. Why doesn't x scrollbar work 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()
The problem here is not the scrollbar code but the assignment of None in wrap config of your textbox.
Change
wrap=None
To
wrap='none'
on an unrelated note
change sticky="n, s, e, w" to sticky="nsew" the commas mean nothing in a quote here. And your other stickys should be "we" and "ns"
You might have been trying to do the tkinter CONSTANTS version of the stick. That would look like this: sticky=(N, S, E, W). However because you did not import * this will not work. You could import each constant from tkinter individually but in this case its best to use sticky="nsew" instead.
Just for reference here is a list of the 'nsew' constants you get when you import * from tkinter
N='n'
S='s'
W='w'
E='e'
NW='nw'
SW='sw'
NE='ne'
SE='se'
NS='ns'
EW='ew'
NSEW='nsew'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With