【问题标题】:How to Decorate Tkinter Text Widget如何装饰 Tkinter 文本小部件
【发布时间】:2020-03-24 03:33:15
【问题描述】:

如何在 Tkinter 上装饰纯文本框,使其变得像 Google 搜索栏:

是否可以在文本小部件中插入一些图像?是否可以将默认文本设置为:“搜索网络”,然后当用户开始向小部件输入文本时,“搜索网络”的默认文本将消失以显示我们的文本?

我试过了:

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

但结果是我需要先删除“搜索网络”,然后再输入文本小部件,这不是我想要的。

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    您需要将<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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 2019-06-14
      • 2014-03-19
      • 1970-01-01
      相关资源
      最近更新 更多