Apr-15-2021, 01:31 AM
I've been looking at adding line numbers to a Text widget. There are several examples floating around the internet, all a bit different in most cases.
I found one that seemed fairly simple to implement as I have only been working with Python for a couple of months.
The code shown below almost works 100% but needs two modifications and this is where I need some help/guidance:
(1) when the app starts up, the line numbers are not filled out...until you press a key.
(2) when a key has been pressed and the line numbers are filled out, scrolling the text down does not change the line numbers. They are always what you see after the first key press. Obviously the line numbers should scroll along with the text but I am not sure how to do that.
Thank you for any help...
I found one that seemed fairly simple to implement as I have only been working with Python for a couple of months.
The code shown below almost works 100% but needs two modifications and this is where I need some help/guidance:
(1) when the app starts up, the line numbers are not filled out...until you press a key.
(2) when a key has been pressed and the line numbers are filled out, scrolling the text down does not change the line numbers. They are always what you see after the first key press. Obviously the line numbers should scroll along with the text but I am not sure how to do that.
Thank you for any help...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
import tkinter as tk class LineNumbers(tk.Text): def __init__( self , master, text_widget, * * kwargs): super ().__init__(master, * * kwargs) self .text_widget = text_widget self .text_widget.bind( '<KeyPress>' , self .on_key_press) self .insert( 1.0 , '1' ) self .configure(state = 'disabled' ) def on_key_press( self , event = None ): final_index = str ( self .text_widget.index(tk.END)) num_of_lines = final_index.split( '.' )[ 0 ] line_numbers_string = "\n" .join( str (no + 1 ) for no in range ( int (num_of_lines))) width = len ( str (num_of_lines)) self .configure(state = 'normal' , width = width) self .delete( 1.0 , tk.END) self .insert( 1.0 , line_numbers_string) self .configure(state = 'disabled' ) if __name__ = = '__main__' : w = tk.Tk() t = tk.Text(w) l = LineNumbers(w, t, width = 2 ) t.insert( '1.0' , 'a\n' \ 'b\n' \ 'c\n' \ 'd\n' \ 'e\n' \ 'f\n' \ 'g\n' \ 'h\n' \ 'i\n' \ 'j\n' \ 'k\n' \ 'l\n' \ 'm\n' \ 'n\n' \ 'o\n' \ 'p\n' \ 'q\n' \ 'r\n' \ 's\n' \ 't\n' \ 'u\n' \ 'v\n' \ 'w\n' \ 'x\n' \ 'y\n' \ 'z\n' \ '1\n' \ '2\n' \ '3\n' \ '4\n' \ '5\n' \ '6\n' \ '7\n' \ '8\n' \ '9\n' ) l.pack(side = tk.LEFT) t.pack(side = tk.LEFT, expand = 1 ) w.mainloop() |