I'm messing around with a notepad application using Tkinter and I would like to have a label centered above the main text box for a user to label the note. I would like to be able to double-click on the label to edit it. When the user clicks out of the label text area then it would save the text there. I understand I could make a simple text area for the user to type into but I would also like it to be centered and not a blinking cursor the entire time. I'm new to messing with Tkinter so maybe there is a simple solution or better approach. Thank you for any help!
CodePudding user response:
You can use a label that is configured so that when you double-click it you overlay an entry widget.
Something like this, for example:
class EditableLabel(tk.Label):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.entry = tk.Entry(self)
self.bind("<Double-1>", self.edit_start)
self.entry.bind("<Return>", self.edit_stop)
self.entry.bind("<FocusOut>", self.edit_stop)
self.entry.bind("<Escape>", self.edit_cancel)
def edit_start(self, event=None):
self.entry.place(relx=.5, rely=.5, relwidth=1.0, relheight=1.0, anchor="center")
self.entry.focus_set()
def edit_stop(self, event=None):
self.configure(text=self.entry.get())
self.entry.place_forget()
def edit_cancel(self, event=None):
self.entry.delete(0, "end")
self.entry.place_forget()
You can then use this like a normal label, like in the following example.
root = tk.Tk()
label = EditableLabel(root, text="double-click to edit me")
text = tk.Text(root)
label.pack(side="top", fill="x", padx=2, pady=2)
text.pack(side="top", fill="both", expand=True)
root.mainloop()