How to make tkinter Text widget scroll only full lines?
Asked Answered
P

1

6

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.

Pelagia answered 24/8 at 19:11 Comment(1)
Try adding return "break" at the end of the function definition. That stops the event from being handled by tkinter which also scrolls the text box. Also, +1 great question with a beautiful minimal working example.Upside
R
0

lets declear the problem first when scroll the text widget the text moved up by integer value in this

text_widget.yview_scroll(...)

this value must has an integer parameter of the font hight and spacing between lines so for each font type and size there is a spacing value will make the full line appears by scrolling so by the code you put without determine a font type or size so there has the default value of the text widget it works for e by chang the spacing value to 1.5 like this.

s = 1.5
text_widget.config(spacing1=s)
text_widget.config(spacing2=s)
text_widget.config(spacing3=s)

remember if you change the font type or size you need to try many time to get the spacing value which make the line appears full

Rank answered 30/8 at 6:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.