While making a small tkinter project in python, I was trying to make a Text widget scroll only full lines, i.e., avoiding it to cut any lines at the top or bottom of the box.
After a bit of search, I came to this code:
text_widget.yview_scroll(int(-1*(event.delta/120)*scroll_lines), "units")
I tried it, but din't work properly, so I wrote a small program on a separate file to check if another part of my project could be interfering with it:
import tkinter as tk
def on_mousewheel(event):
# Scroll by a custom number of lines
text_widget.yview_scroll(int(-1*(event.delta/120)), "units")
root = tk.Tk()
# Create a Text widget
text_widget = tk.Text(root, wrap="word")
text_widget.pack(fill="both", expand=True)
# Bind the mouse wheel event to the custom scroll function
text_widget.bind("<MouseWheel>", on_mousewheel)
# Add some content to the Text widget
for i in range(100):
text_widget.insert("end", f"Line {i+1}\n")
root.mainloop()
This produced the same wrong result as the anterior: instead of scrolling one full line, it scrolls 3.5 lines, resulting on the first and last visible ones getting cut in half. Is there any error in my code, or could this be a problem of my computer or python/tkinter version? I'm using Windows, Python 3.11.4 and Tkinter 8.6.12.
return "break"
at the end of the function definition. That stops the event from being handled bytkinter
which also scrolls the text box. Also, +1 great question with a beautiful minimal working example. – Upside