I am trying to make the text kind of disabled in the background. But the user also cannot write text when I make it disabled
The question was already asked by someone, But those answers were not clear to me and were not satisfying. So I decided to post this question.
I want the text to be similar to the input fields on the login pages of most websites, where some text like 'Username' or 'Password' is already written in the input fields.
So the text should be a little bit faint, and when the users starts typing the text should disappear. So The user should not be able to copy it and doesn't need to remove it before typing.
This is what I tried but it didn't work.
from tkinter import *
root = Tk()
my_entry = Entry(root, width=50)
my_entry.pack()
my_entry.insert(0, "Enter Your Name")
my_entry.configure(state=DISABLED)
root.mainloop()
The user also cannot write text in the input field.
Does this help you?
from tkinter import *
root = Tk()
my_entry = Entry(root, width=50)
my_entry.pack()
my_entry.insert(0, "Enter Your Name")
my_entry.configure(state=DISABLED)
def on_click(event):
my_entry.configure(state=NORMAL)
my_entry.delete(0, END)
# make the callback only work once
my_entry.unbind('<Button-1>', on_click_id)
on_click_id = my_entry.bind('<Button-1>', on_click)
root.mainloop()
As a class:
import tkinter as tk
class DefaultEntry(tk.Entry):
def __init__(self, master=None, default_text='', **kw):
super().__init__(master, **kw)
self.insert(0, default_text)
self.configure(state=tk.DISABLED)
self.on_click_id = self.bind('<Button-1>', self.on_click)
def on_click(self, _):
self.configure(state=tk.NORMAL)
self.delete(0, tk.END)
# unregister myself
self.unbind('<Button-1>', self.on_click_id)
root = tk.Tk()
my_entry = DefaultEntry(root, width=50, default_text='Enter your Name')
my_entry.pack()
root.mainloop()