abhishek bhardwaj
abhishek bhardwaj

Reputation: 31

How to use button as scrollbar in tkinter

I want to use buttons as scrollbar in Tkinter. Like there are two button on screen (up,down) and scrollbar (Y axis), we can use scrollbar to move screen up and down or when down is pressed screen goes down and when up is pressed screen goes up. How this can be done?

Upvotes: 2

Views: 190

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385970

Scrollable widgets have methods for scrolling the widget - yview for scrolling up and down, and xview for scrolling left and right. It's the very same methods called by the scrollbar. You can directly call these methods in your code.

For example, something like the_text_widget.yview_scroll(1, "pages") will scroll down one "page". You can use units to scroll down a "unit", which is one line in a text widget or listbox, and some small number of pixels in a canvas.

Here's a simple example:

import tkinter as tk

root = tk.Tk()
toolbar = tk.Frame(root)
text = tk.Text(root, wrap="word")
vsb = tk.Scrollbar(root, command=text.yview)
text.configure(yscrollcommand=vsb.set)
toolbar.pack(side="top", fill="x")
vsb.pack(side="right", fill="y")
text.pack(side="left", fill="both", expand=True)

def down():
    text.yview_scroll(1, "pages")
def up():
    text.yview_scroll(-1, "pages")

down_button = tk.Button(toolbar, text="Down", width=4, command=down)
up_button = tk.Button(toolbar, text="Up", width=4, command=up)
down_button.pack(side="left")
up_button.pack(side="left")

for i in range(1000):
    text.insert("end", f"Line #{i+1}\n")

root.mainloop()

Upvotes: 1

Related Questions