Crabime
Crabime

Reputation: 684

subclass Label in tkinter

I need to subclass a Label widget, so that the browser can open a link while the mouse clicks on it.

Here is the code snippet of what I've done so far.

from tkinter import *
import webbrowser

class HyperLinkLabel(Label):

    def __init__(self, link, *args, **kwargs):
        Label.__init__(self, *args, **kwargs)
        self.link = link
        self.bind("<Button-1>", self.click_callback)

    def click_callback(self):

        webbrowser.open_new(self.link)

if __name__ == '__main__':
    master = Tk()
    root = Frame(master)
    label1 = HyperLinkLabel(root, link='https://www.google.com')
    label1.config(text='hello')
    label1.pack()
    root.master.minsize(100, 50)
    root.mainloop()

Upvotes: 1

Views: 642

Answers (1)

falsetru
falsetru

Reputation: 369094

  • You should declare master (or parent) parameter and pass it to Label constructor. (root from the perspect of caller)
  • event handle should have event parameter even though you don't use it. Otherwise TypeError exception is thrown.
  • Pack frame so that widgets inside it is visible.

from tkinter import *
import webbrowser

class HyperLinkLabel(Label):
    def __init__(self, master, link, *args, **kwargs):  # <-- pass master parameter
        Label.__init__(self, master, *args, **kwargs)   # <-- pass master parameter
        self.link = link
        self.bind("<Button-1>", self.click_callback)

    def click_callback(self, event):  # <--- missed event parameter
        webbrowser.open_new(self.link)

if __name__ == '__main__':
    master = Tk()
    root = Frame(master)
    label1 = HyperLinkLabel(root, link='https://www.google.com')
    label1.config(text='hello')
    label1.pack()
    root.pack()   # <-- should pack frame; otherwise link widget is not visible
    root.master.minsize(100, 50)
    root.mainloop()

Upvotes: 3

Related Questions