0

I have an issue where I've created a text widget inside a tkinter Frame that is suppose to center the text on the first line when the user types. It does this, except the first letter they type it justify's it to the left then after a second letter is pressed it justify's to the center as expected.

I would like to know how to fix this so the first line stays centered.

Here is the code I've gotten so far:

import Tkinter as tk

def testing(event=None, text=None):
    LineNumber = text.index(tk.INSERT) # returns line number

    if "1." in LineNumber:
        text.tag_add("center", "1.0", "end")

root = tk.Tk()

F1 = tk.Frame(root, bg="blue", width=300, height=300)
F1.pack()

text = tk.Text(F1, padx=5, pady=10, bg="white")
text.tag_configure("center", justify='center')
text.pack(expand=1, fill="both")

text.bind('<Key>', lambda event: testing(None, text))

root.mainloop()
Davidhall
  • 35
  • 11

1 Answers1

1

It is because your custom binding fires before tkinter has a chance to insert the character. When you press a key, the first thing that happens is that your custom binding is triggered, before any other bindings. The character has not been inserted yet.

For a full explanation of how key events are processed, see this answer: https://stackoverflow.com/a/11542200/7432

A simple fix is to bind on <KeyRelease> instead of <Key>. Since the default behavior happens on a press (but after your custom behavior), a binding on the release of the key will be guaranteed to run after the character has been inserted into the widget.

Community
  • 1
  • 1
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685