0

I was looking around the web for a "selectable label" in tkinter, everyone seems to point to a disabled text entry. I wanted to share mine thus far. I plan to modify this so that when the label is selected, you can click an "edit" button elsewhere in the program and then do something to the label.

import tkinter as tk

class SelectableLabel(tk.Label):
    def __init__(self, parent, text="", bg="white", fg="black"):
        tk.Label.__init__(self, parent)
        self.text = text
        self.bg = bg
        self.fg = fg
        self.config(text=text, bg=bg, fg=fg)
        self.bind('<Enter>', lambda x: self._label_enter())
        self.bind('<Leave>', lambda x: self._label_leave())
        self.bind('<Button-1>', lambda x: self._label_action())

    @staticmethod
    def _label_enter():
        label.config(bg="black", fg="white")

    @staticmethod
    def _label_leave():
        label.config(bg="white", fg="black")

    @staticmethod
    def _label_action():
        print("Label Selected")

root = tk.Tk()
root.geometry("400x400")
label = SelectableLabel(root, text="Test Label")
label.pack()

root.mainloop()
2
Contributors
1
Reply
17
Views
7 Months
Discussion Span
Last Post by woooee
0

You don't need the lambdas. You are executing the function (parens follow function name) so that requires a lambda. Just pass the function reference.

self.bind('<Enter>', self._label_enter)  ## no parens
## and then
def _label_enter(event=None):
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.