Issue
I have a textbox widget that has 2 event bindings like so:
F2_text_editor.bind('<Return>', lambda e: on_key_release())
F2_text_editor.bind("<BackSpace>", lambda e: on_key_release(), add="+")
I am working on adding line numbers to my text editor. All is well so far but the last issue I have encountered is not one I think is fixable?
Basically what is happening is that when I press either binded key on my keyboard its executed the function, then completes the action from the keyboard itself.
For example let's say I have a binding and a function that prints out a message. When I hit Return, it will print out the message and then move the cursor to the next line. Is there a way to reverse this?
Here the code:
def on_key_release():
print("on_key_release")
#F2_line_numbers.delete("1.0", "end")
final_index = str(F2_text_editor.index("end-1c"))
print(f"final_index: {final_index}")
num_of_lines = final_index.split('.')[0]
print(f"num_of_lines: {num_of_lines}")
line_numbers_string = "\n".join(str(no + 1) for no in
range(int(num_of_lines)))
#print(f"line_numbers_string: {line_numbers_string}")
width = len(str(num_of_lines))
#print(f"width: {width}")
F2_line_numbers.configure(state='normal', width=width)
F2_line_numbers.delete("1.0", "end")
F2_line_numbers.insert("1.0", line_numbers_string)
F2_line_numbers.configure(state='disabled')
The reason I need to reverse the 'event/handler' priority is because when I am on line 1 for example and hit Return, that function prints out 'index 1.0 / num of line: 1' when I am on line 2. Then I hit Backspace and it says I am on line 2 when I am on line 1.
UPDATE: I thought I would try and add a wait to the handler function but all it did was force the event to wait till the handler had been executed. Another feature I am working on also needs the event/handler priority to be reversed too so I am really hoping someone knows how to do this.
Solution
I solved this by using threading.
The function binded to the widget contains a thread to another function that handles the line number think. Now when I am on line 1 and hit enter it shows line 2. I then hit backspace and it shows line 1 just as it should. Threading is allowing the event to occur before the function which is exactly what I wanted.
Answered By - phil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.