How to Add Placeholder to an Entry in Tkinter

How to add placeholder to an Entry in tkinter?

You need to set a default value for this entry. Like this:

from tkinter import *

ui = Tk()

e1 = Entry(ui)
e1.insert(0, 'username')
e1.pack()

ui.mainloop()

Then if you want to delete the content when you click the entry, then you have to bind a mouse click event with an event handler method to update content of this entry.
Here is a link for you.

Adding placeholders to tkinter Entry widget in a procedural way

Here is a very simple example. In this example we include a couple of features/caveats:

  • ghost text for the placeholder
  • entry.input will return None if it's text is the placeholder or empty
  • entry.input should be used in place of .get() and .insert(). The .input logic is designed to give you the proper results for this type of widget. .get() is not smart enough to return the proper data, and .insert() has been reconfigured as a proxy to .input
  • placeholder is juggled while you type
  • placeholder can be overwritten with .insert() ~ no need to use .delete(). You should still use entry.input instead


#widgets.py

import tkinter as tk

class PlaceholderEntry(tk.Entry):
'''
All Of These Properties Are For Convenience
'''
@property
def input(self):
return self.get() if self.get() not in [self.__ph, ''] else None

@input.setter
def input(self, value):
self.delete(0, 'end')
self.insert(0, value)
self.configure(fg = self.ghost if value == self.__ph else self.normal)

@property
def isempty(self) -> bool:
return self.get() == ''

@property
def isholder(self) -> bool:
return self.get() == self.__ph

def __init__(self, master, placeholder, **kwargs):
tk.Entry.__init__(self, master, **{'disabledforeground':'#BBBBBB', **kwargs})

self.normal = self['foreground']
self.ghost = self['disabledforeground']

self.__ph = placeholder
self.input = placeholder

vcmd = self.register(self.validate)
self.configure(validate='all', validatecommand=(vcmd, '%S', '%s', '%d'))

self.bind('<FocusIn>' , self.focusin)
self.bind('<FocusOut>', self.focusout)
self.bind('<Key>' , self.check)

#rewire .insert() to be a proxy of .input
def validate(self, action_text, orig_text, action):
if action == '1':
if orig_text == self.__ph:
self.input = action_text

return True

#removes placeholder if necessary
def focusin(self, event=None):
if self.isholder:
self.input = ''

#adds placeholder if necessary
def focusout(self, event=None):
if self.isempty:
self.input = self.__ph

#juggles the placeholder while you type
def check(self, event):
if event.keysym == 'BackSpace':
if self.input and len(self.input) == 1:
self.input = self.__ph
self.icursor(0)
return 'break'
elif self.isholder:
if event.char:
self.input = ''
else:
return 'break'

usage example:

#__main__.py

import tkinter as tk
import widgets as ctk #custom tk


if __name__ == "__main__":
root = tk.Tk()
root.title("Placeholder Entry")
root.grid_columnconfigure(2, weight=1)

#init some data
entries = [] #for storing entry references
label_text = ['email', 'name']
entry_text = ['you@mail.com', 'John Smith']

#create form
for n, (label, placeholder) in enumerate(zip(label_text, entry_text)):
#make label
tk.Label(root, text=f'{label}: ', width=8, font='consolas 12 bold', anchor='w').grid(row=n, column=0, sticky='w')
#make entry
entries.append(ctk.PlaceholderEntry(root, placeholder, width=14, font='consolas 12 bold'))
entries[-1].grid(row=n, column=1, sticky='w')

#form submit function
def submit():
for l, e in zip(label_text, entries):
if e.input:
print(f'{l}: {e.input}')

#form submit button
tk.Button(root, text='submit', command=submit).grid(column=1, sticky='e')

root.mainloop()



How to add a placeholder in Tkinter

U can't add placeholder like HTML as far as i know, but u can make similar behavior. When you make entry you can do something like>

from tkinter import *   

def clear_entry(event, entry):
entry.delete(0, END)

root = Tk()

entry = Entry(root)

entry.pack()
placeholder_text = 'some text'
entry.insert(0, placeholder_text)

entry.bind("<Button-1>", lambda event: clear_entry(event, entry))

root.mainloop()

P.S: I've wrote this from my head , haven't tested it

How can I center a placeholder text in an Entry with tkinter?

You can use justify option to center the placeholder:

def put_placeholder(self):
self.insert(0, self.placeholder)
self['fg'] = self.placeholder_color
self['justify'] = 'center' # center the placeholder

def foc_in(self, *args):
if self['fg'] == self.placeholder_color:
self.delete('0', 'end')
self['fg'] = self.default_fg_color
self['justify'] = 'left' # left justify for normal input

User entering same placeholder text python tkinter

Since you have a custom class, it's easy to set a flag when you add the placeholder text, and easy to unset it when you remove the placeholder. Then it's just a matter of checking whether or not the flag is set when you get the value.

def add(self, *args):
if self.get() == '': # if no text add placeholder
...
self._has_placeholder = True

def clear(self, *args):
if self.get() == self.text: # remove placeholder when focus gain
self._has_placeholder = False
...


Related Topics



Leave a reply



Submit