2

I am a little new to tkinter in Python 3 and I am trying to create a scroll bar to work with many widgets like Labels and Radio Buttons. What I have works so far but the scrolling only works when I hover the scroll bar. I would like to get it to work everywhere in the window.

I found another post in Tkinter scroll bar not scrolling with the same issue as me but trying the solution did not solve my problem.

Here is a very dummed down example of what I am trying to produce

import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root)
scrolly = tk.Scrollbar(root, orient='vertical', command=canvas.yview)

for i in range(60):
    label = tk.Label(canvas, text=i)
    canvas.create_window(0, 20 * i, window=label)

canvas.configure(scrollregion=canvas.bbox('all'), yscrollcommand=scrolly.set)

canvas.pack(fill='both', expand=True, side='left')
scrolly.pack(fill='y', side='right')

root.mainloop()

I would like to be able to scroll the page without having to hover on the scroll bar

Thank you for the help in advance

Brandalf
  • 476
  • 1
  • 6
  • 20
  • 1
    What I'm hearing is "It's inconvenient that the only way to scroll is to put my cursor over the scroll bar and click on it and/or drag it". Certainly, that's a valid frustration. What alternative did you have in mind? Do you want the user to be able to click and drag on the canvas contents in order to pan around? Or should they be able to use their scroll wheel? Or something else? – Kevin Apr 29 '19 at 18:32
  • `bind()` + `""` will help you out here. – Mike - SMT Apr 29 '19 at 19:42

1 Answers1

2
def _on_mousewheel(event):
    canvas.yview_scroll(int(-1*(event.delta/120)), "units")
canvas.bind_all("<MouseWheel>", _on_mousewheel)

This working with mouse wheel

https://stackoverflow.com/a/17457843/7590574


Another Idea:

import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root)
scrolly = tk.Scrollbar(root, orient='vertical', command=canvas.yview)

pressedY = 0

def mouse_pressed(e, label):
    pressedY = e.y
    print('p',e, label)

def mouse_released(e, label):
    print('r',e, label)

def mouse_motion(e, label):
    m = pressedY - e.y
    # print('m',e, label)
    canvas.yview_scroll(int(-1*(m/50)), "units")


labelList = []
for i in range(60):
    labelList.append(tk.Label(canvas, text=i))
    canvas.create_window(0, 20 * i, window=labelList[i])

    labelList[i].bind("<Button-1>",lambda e,i=i:mouse_pressed(e, labelList[i]))
    labelList[i].bind("<ButtonRelease-1>",lambda e,i=i:mouse_released(e, labelList[i]))
    labelList[i].bind("<B1-Motion>",lambda e,i=i:mouse_motion(e, labelList[i]))

canvas.configure(scrollregion=canvas.bbox('all'), yscrollcommand=scrolly.set)

canvas.pack(fill='both', expand=True, side='left')
scrolly.pack(fill='y', side='right')

root.mainloop()
Wang Liang
  • 4,244
  • 6
  • 22
  • 45