Search code examples
pythontkintertkinter-entrypad

Python Tkinter Entry pad text


How could I pad the entry widget so it does not start writing right at the border of the widget? Visually, having a little space from the entry widget border.

My progress:

entry_widget.bind('<FocusIn>', lambda f: entry_widget.insert(0, ' '))

That adds an empty space when the user clicks the widget but there are multiple issue with this solution:

  1. When clicking out and clicking back in, it will add another space on top of the empty space or any text the user had filled in. I considered clearing the entry widget on FocusOut but that would also clear all the text that the user might have written.

  2. The user can delete the inserted space

  3. when getting the content, there is the additional space at the beginning. Though this is a small problem which can be solved by removing the first character of the content.

And there might be more issues which I did not account for.

I think the way where my code is heading is bad, therefore I am asking if anyone has any idea how to 'properly' pad the entry widget?


Solution

  • I'm not aware a native way of adjusting the Entry's padding, but here's one way to get something like it. Make the entry's border invisible by giving it a FLAT style, and embed the entry in a Frame that acts as the entry's border. Then you can specify the padding by adjusting the entry's borderwidth. Example:

    import tkinter as tk
    
    root = tk.Tk()
    frame = tk.Frame(root, borderwidth=5, relief=tk.SUNKEN)
    frame.pack()
    entry = tk.Entry(frame, borderwidth=15, relief=tk.FLAT)
    entry.pack()
    root.mainloop()
    

    Result:

    enter image description here