Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prepopulate a text field with suggested text in Tkinter?

Tags:

python

tkinter

I'm trying to prepopulate a text field based on the most recent entry. As this is not a Listbox, I don't see how to do it, and I'm not seeing any examples on the web. Thanks.

Update. I've managed to find a partial way of doing this. Still wondering, is it possible to supply suggested text in Tkinter which fades when the text box is clicked?

from Tkinter import *

app = Tk()
app.title("GUI Example")
app.geometry('560x460+200+200')

x = Text(app)
x.insert(END, "Before")
x.pack()

def replace():
    x.delete(1.0, END)
    x.insert(END, "After")

abutton = Button(app, text="Click me", command=replace)
abutton.pack()

app.mainloop()
like image 283
zadrozny Avatar asked Oct 22 '25 09:10

zadrozny


1 Answers

Well, I personally don't know of any options to do this (any answers giving one will easily trump this one).

However, you can closely mimic this behavior with a little coding. Namely, you can bind the textbox to a function that will insert/remove the default text for you.

Below is a simple script to demonstrate:

import Tkinter as tk

tk.Tk()

textbox = tk.Text(height=10, width=10)
textbox.insert(tk.END, "Default")
textbox.pack()

# This is for demonstration purposes
tk.Text(height=10, width=10).pack()

def default(event):
    current = textbox.get("1.0", tk.END)
    if current == "Default\n":
        textbox.delete("1.0", tk.END)
    elif current == "\n":
        textbox.insert("1.0", "Default")

textbox.bind("<FocusIn>", default)
textbox.bind("<FocusOut>", default)

tk.mainloop()

Notice how:

  1. When you click in the top textbox, the default text disappears.

  2. When you click in the bottom textbox, the top one loses focus and the default text reappears.

  3. This behavior will only occur if there is nothing in the top textbox.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!