Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_custom_scrollbar.py
- import tkinter as tk
- def custom_scrollbar(master, target, orient=tk.VERTICAL, width=10):
- def set_scrollbar(scrollbar, low, high):
- low = float(low)
- high = float(high)
- cv.thumb_position = low
- cv.thumb_size = high - low
- redraw_scrollbar()
- def redraw_scrollbar():
- cv.delete("sbar")
- if cv.orient == tk.VERTICAL:
- thumb_height = cv.winfo_height() * cv.thumb_size
- thumb_y = cv.winfo_height() * cv.thumb_position
- cv.create_rectangle(0, thumb_y, cv.winfo_width(), thumb_y + thumb_height, fill="gray", tag="sbar")
- else:
- thumb_width = cv.winfo_width() * cv.thumb_size
- thumb_x = cv.winfo_width() * cv.thumb_position
- cv.create_rectangle(thumb_x, 0, thumb_x + thumb_width, cv.winfo_height(), fill="gray", tag="sbar")
- def on_press(event):
- if cv.orient == tk.VERTICAL:
- cv.dragging = event.y
- else:
- cv.dragging = event.x
- update_command()
- def on_motion(event):
- if cv.dragging is not False:
- if cv.orient == tk.VERTICAL:
- delta = event.y - cv.dragging
- cv.dragging = event.y
- cv.thumb_position += delta / cv.winfo_height()
- else:
- delta = event.x - cv.dragging
- cv.dragging = event.x
- cv.thumb_position += delta / cv.winfo_width()
- cv.thumb_position = max(0, min(1 - cv.thumb_size, cv.thumb_position))
- redraw_scrollbar()
- update_command()
- def on_release(event):
- cv.dragging = False
- def update_command():
- cmd("moveto", cv.thumb_position)
- cmd = target.yview
- cv = tk.Canvas(master, width=width)
- cv.orient = orient # Set the orient attribute
- cv.bind("<ButtonPress-1>", lambda event: on_press(event))
- cv.bind("<B1-Motion>", lambda event: on_motion(event))
- cv.bind("<ButtonRelease-1>", lambda event: on_release(event))
- cv.dragging = False
- cv.thumb_position = 0.0
- cv.thumb_size = 0.0
- target.config(yscrollcommand=lambda low, high: set_scrollbar(scrollbar, low, high))
- return cv
- root = tk.Tk()
- listbox = tk.Listbox(root, height=10, width=20)
- listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
- scrollbar = custom_scrollbar(root, listbox, orient=tk.VERTICAL)
- scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
- for i in range(100):
- listbox.insert(tk.END, f"Item {i}")
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement