Adding Link To Text In Text Widget In Tkinter
I am creating a song notification program in python using Tkinter and bs4. I have extracted songs and their corresponding urls from a site. I have used text widget to store songs a
Solution 1:
I had no problem. Create a file called "tkHyperlinkManager.py" that contains:
from tkinter import *
classHyperlinkManager:
def__init__(self, text):
self.text = text
self.text.tag_config("hyper", foreground="blue", underline=1)
self.text.tag_bind("hyper", "<Enter>", self._enter)
self.text.tag_bind("hyper", "<Leave>", self._leave)
self.text.tag_bind("hyper", "<Button-1>", self._click)
self.reset()
defreset(self):
self.links = {}
defadd(self, action):
# add an action to the manager. returns tags to use in# associated text widget
tag = "hyper-%d" % len(self.links)
self.links[tag] = action
return"hyper", tag
def_enter(self, event):
self.text.config(cursor="hand2")
def_leave(self, event):
self.text.config(cursor="")
def_click(self, event):
for tag in self.text.tag_names(CURRENT):
if tag[:6] == "hyper-":
self.links[tag]()
return
Import it to your program and insert links. I've supplied sample data which seems reasonable. The list of Bollywood songs are with hyperlinks and the list of International songs are not. I'ts just a demonstration of the mechanism. You will have to write all the callbacks and web interface yourself.
from tkinter import *
from tkHyperlinkManager import *
b_songs_list = ['Bollywood song 1','Bollywood song 2','Bollywood song 3']
i_songs_list = ['International song 1','International song 2','International song 3']
root = Tk()
S = Scrollbar(root)
T = Text(root, height=20, width=30,cursor="hand2")
hyperlink = HyperlinkManager(T)
S.pack(side=RIGHT, fill=Y)
T.pack(side=LEFT, fill=Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
defclick1():
print('click1')
defcallback_a(): # Bollywood songs WITH hyperlinks
T.delete(1.0,END)
for songs inb_songs_list:
T.insert(END, songs, hyperlink.add(click1))
T.insert(END, '\n')
defcallback_b():
T.delete(1.0,END)
for songs ini_songs_list:
T.insert(END, songs + '\n')
bollywood_button = Button(root,text="Bollywood-Top-50", command=callback_a)
bollywood_button.pack()
international_button = Button(root,text="International-Top-50", command=callback_b)
international_button.pack()
Post a Comment for "Adding Link To Text In Text Widget In Tkinter"