Allan Tanaka
Allan Tanaka

Reputation: 307

How to Decorate Tkinter Text Widget

How can I decorate a plain textbox on Tkinter to become like Google search bar: enter image description here

Is it possible to insert some image to text widget? Is it possible to set default text to: "Search the Web", then when the user start typing text to widget, the default text of "Search the Web" will disappear in order to show our text?

I tried:

textBox = Text(root)
text.insert("END", "Search the Web")

But the result is that I need to delete "Search the Web" first before I type to text widget, which is not what I want.

Upvotes: 0

Views: 352

Answers (1)

acw1668
acw1668

Reputation: 46688

You need to bind <FocusIn> to a callback, then in the callback remove the placeholder if it exists.

Also bind <FocusOut> to another callback and insert back the placeholder if current content of the text box is empty.

Below is an example:

import tkinter as tk

class Textbox(tk.Text):
    # create the google image
    tkimg = None

    def __init__(self, parent, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        if self.tkimg is None:
            self.tkimg = tk.PhotoImage(file='images/google16x16.png')
        self.insert_placeholder()
        self.bind('<FocusIn>', self.on_focus_in)
        self.bind('<FocusOut>', self.on_focus_out)

    def insert_placeholder(self):
        ''' insert the placeholder into text box '''
        lbl = tk.Label(self, text='Search the Web', image=self.tkimg, compound='left',
                       fg='darkgray', bg=self.cget('bg'), font=(None,10,'bold'))
        self.window_create('end', window=lbl)
        self.placeholder = self.window_names()[0]

    def on_focus_in(self, event):
        try:
            # check whether the placeholder exists
            item = self.window_cget(1.0, 'window')
            if item == self.placeholder:
                # remove the placeholder
                self.delete(1.0, 'end')
        except:
            # placeholder not found, do nothing
            pass

    def on_focus_out(self, event):
        if self.get(1.0, 'end-1c') == '':
            # nothing input, so add back the placeholder
            self.insert_placeholder()

root = tk.Tk()

Textbox(root, height=10).pack()
Textbox(root, height=5).pack()

root.mainloop()

enter image description here

Upvotes: 2

Related Questions