Default Text As Well As List Textvariable Entry Widget Tkinter
I have the following Entry box where due to obtaining values I have put a list option in for textvariable. However I was wondering if it would be possible to put a default text in
Solution 1:
In order to put default text in your Entry
widget, you can use the insert()
method as described here.
box.insert(0, "Value 1") # Set default text at cursorposition0.
Now in order to change the contents of box
after the user performs a mouse click inside the box, you will need to bind an event to the Entry
object. For example, the following code deletes the contents of the box when it is clicked. (You can read about event and bindings here.) Below I show a full example of this.
Note that deleting the text in the box is probably only practical for the first click (i.e. when deleting the default contents), so I created a global flag clicked
to keep track of whether it has been clicked.
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.defcallback(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()
Post a Comment for "Default Text As Well As List Textvariable Entry Widget Tkinter"