How to create a hyperlink with a Label in Tkinter?

后端 未结 4 1026
逝去的感伤
逝去的感伤 2020-12-01 14:21

How do you create a hyperlink using a Label in Tkinter?

A quick search did not reveal how to do this. Instead there were only solutions

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 14:53

    you can create a class that inherits from label widget of tkinter module , initialize it with additional values including the link of course ... then you create an instance of it as shown below.

    import tkinter as t
    import webbrowser
    
    
    class Link(t.Label):
        
        def __init__(self, master=None, link=None, fg='grey', font=('Arial', 10), *args, **kwargs):
            super().__init__(master, *args, **kwargs)
            self.master = master
            self.default_color = fg # keeping track of the default color 
            self.color = 'blue'   # the color of the link after hovering over it 
            self.default_font = font    # keeping track of the default font
            self.link = link 
    
            """ setting the fonts as assigned by the user or by the init function  """
            self['fg'] = fg
            self['font'] = font 
    
            """ Assigning the events to private functions of the class """
    
            self.bind('', self._mouse_on)    # hovering over 
            self.bind('', self._mouse_out)   # away from the link
            self.bind('', self._callback) # clicking the link
    
        def _mouse_on(self, *args):
            """ 
                if mouse on the link then we must give it the blue color and an 
                underline font to look like a normal link
            """
            self['fg'] = self.color
            self['font'] = self.default_font + ('underline', )
    
        def _mouse_out(self, *args):
            """ 
                if mouse goes away from our link we must reassign 
                the default color and font we kept track of   
            """
            self['fg'] = self.default_color
            self['font'] = self.default_font
    
        def _callback(self, *args):
            webbrowser.open_new(self.link)  
    
    
    root = t.Tk()
    root.title('Tkinter Links !')
    root.geometry('300x200')
    root.configure(background='LightBlue')
    
    URL = 'www.python.org'
    
    link = Link(root, URL, font=('sans-serif', 20), text='Python', bg='LightBlue')
    link.pack(pady=50)
    
    root.mainloop()
    

提交回复
热议问题