簡體   English   中英

如何裝飾 Tkinter 文本小部件

[英]How to Decorate Tkinter Text Widget

如何在 Tkinter 上裝飾純文本框以變得像 Google 搜索欄: 在此處輸入圖片說明

是否可以在文本小部件中插入一些圖像? 是否可以將默認文本設置為:“搜索網絡”,然后當用戶開始向小部件輸入文本時,“搜索網絡”的默認文本將消失以顯示我們的文本?

我試過:

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

但結果是我需要先刪除“搜索網絡”,然后再輸入文本小部件,這不是我想要的。

您需要將<FocusIn>綁定到回調,然后在回調中刪除占位符(如果存在)。

如果文本框的當前內容為空, <FocusOut>綁定到另一個回調並插入占位符。

下面是一個例子:

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()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM