默认文本以及列表textvariable Entry小部件Tkinter

时间:2012-07-04 14:32:08

标签: python list user-interface tkinter ttk

我有以下条目框,由于获取值,我已为textvariable放置了一个列表选项。

但是我想知道是否可以在后台放置默认文本,以便显示每个框中需要哪些值(如灰度文本,'值1,值2等)。

self.numbers = [StringVar() for i in xrange(self.number_boxes) ] #Name available in global scope.       
box=Entry(self.frame_table,bg='white',borderwidth=0, width=10, justify="center", textvariable=self.numbers[i])

我可以在框内点击鼠标时添加更改'textvariable'的内容,还是只需添加另一个textvariable或text来设置默认文本?

  self.box = []

  for i in xrange(self.number_boxes):

        self.clicked = False
        self.box.append(Entry(self.frame_table,bg='white',borderwidth=0, width=10, justify="center", textvariable=self.numbers[i], fg='grey'))
        self.box[i].grid(row=row_list,column=column+i, sticky='nsew', padx=1, pady=1) 
        self.box[i].insert(0, "Value %g" % float(i+1))
        self.box[i].bind("<Button-1>", self.callback)

1 个答案:

答案 0 :(得分:4)

为了将默认文字放在Entry窗口小部件中,您可以使用here所述的insert()方法。

box.insert(0, "Value 1")    # Set default text at cursor position 0.

现在,为了在用户在框内执行鼠标单击后更改box的内容,您需要事件绑定到Entry对象。例如,以下代码在单击时删除框的内容。 (您可以阅读有关事件和绑定here的内容。)下面我将展示一个完整的示例。

请注意,删除框中的文本可能仅适用于第一次单击(即删除默认内容时),因此我创建了一个全局标记clicked来跟踪是否已单击。< / p>

from tkinter import Tk, Entry, END    # Python3. For Python2.x, import Tkinter.

# Use this as a flag to indicate if the box was clicked.
global clicked   
clicked = False

# Delete the contents of the Entry widget. Use the flag
# so that this only happens the first time.
def callback(event):
    global clicked
    if (clicked == False):
        box[0].delete(0, END)         #  
        box[0].config(fg = "black")   # Change the colour of the text here.
        clicked = True

root = Tk()
box = []                              # Declare a list for the Entry widgets.

box.append(Entry(fg = "gray"))        # Create an Entry box with gray text.
box[0].bind("<Button-1>", callback)   # Bind a mouse-click to the callback function.
box[0].insert(0, "Value 1")           # Set default text at cursor position 0.

box.append(Entry(fg = "gray"))        # Make a 2nd Entry; store a reference to it in box.
box[1].insert(0, "Value 2")

box[0].pack()                         #
box[1].pack()

if __name__ == "__main__":
    root.mainloop()