Devin Maharjan
Devin Maharjan

Reputation: 67

How to make the scrollbar in the window to work?

The scrollbar is there, the mousewheel is also binded but the scrollbar itself isn't acting the way it should. The scrollbar just stays on it's place and doesn't act in realtime. What should be done?

import tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk



def on_window1():

    top = tk.Toplevel()
    top.wm_geometry("794x470")
    top.title('Optimized Map 1')


    frame = tk.Frame(top)
    frame.grid(row=3, column=0)

    canvas1 = tk.Canvas(top, width=400, height=280)
    canvas1.grid(row=0,column=200)

    for i in range(40):
        l3 = tk.Label(canvas1, text="Number of Rectangles:" + str(i))
        canvas1.create_window(50,21*i, window=l3, anchor=tk.NW)

    myscrollbar= tk.Scrollbar(top,orient=tk.VERTICAL,command=canvas1.yview)
    myscrollbar.grid(row=0,column=200, sticky=tk.NS)
    #canvas1.configure(yscrollcommand=myscrollbar.set)
    canvas1.bind_all('<MouseWheel>', lambda event: canvas1.yview_scroll(int(-1*(event.delta/120)), "units"))



    #l4 = tk.Label(canvas1, text="Number of Rectangles:")
    #canvas1.create_window(50,21, window=l4, anchor=tk.NW)

window = tk.Tk()


b1 = tk.Button(window, text="Next", command=on_window1)
b1.grid(row=0, column=0)

window.mainloop()

Upvotes: 1

Views: 36

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385860

You have to configure the scrollregion attribute of the canvas, which tells tkinter how much of the virtual canvas is being used. Most often, this is set to the bounding box as returned by the bbox command.

The bbox command returns the coordinates of a box that contains a set of elements. If you pass it the string "all" it will return the coordinates of a box that encompasses all objects in the canvas.

Once you've added everything to the canvas, add this line of code:

canvas1.configure(scrollregion=canvas1.bbox("all"))

Upvotes: 1

Related Questions