Search code examples
pythontkinterpython-webbrowser

Python tkinter:Browser opens automatically without clicking the text


I am developing a project using python and tkinter wherein content in the text widget changes dynamically according to the program.Now in my text widget I have added many urls.And upon clicking them web browser should open.

http://effbot.org/zone/tkinter-text-hyperlink.htm I referred this to create hyperlinks in my code.But now my problem is browser opens up whenever url is displayed on the text widget whithout even clicking on it.

Here is my code.

def click1(self,url): 
    webbrowser.open(url)

restitle,resthumb,resurl=printit()#title,thumbnailimage,url array
while restitle:
    raw_data = urllib.request.urlopen(resthumb[0]).read()
    tim = PIL.Image.open(io.BytesIO(raw_data))
    tim = tim.resize((100, 100), PIL.Image.ANTIALIAS)
    timage = ImageTk.PhotoImage(tim)
    Lb1.image_create(END, image=timage)
    curl=resurl[0]
    Lb1.update()
    images.append(timage)
    Lb1.insert(END,restitle,hyperlink.add(click1(resurl[0])))#Passing url
    Lb1.insert(END,"\n")
    restitle.pop(0)
    resurl.pop(0)
    resthumb.pop(0)

My question: I need to know how to open the browser only on clicking a particular text(hyperlinks) and not when they are added to the text widget.I am new to python and tkinter sorry for any errors in the code snippet.Thanks in advance.


Solution

  • The issue here, is that you cannot pass the function directly to this method hyperlink.add, it will be executed since you call it with an argument. (Note that in the example shown in your link, we only pass the reference of the function without calling it).

    You could use a lambda expression if the parameter was the same for all rows, but the url need to change every time, so, you need to use something like the partial tool :

    from functools import partial
    
    [...]
    
    Lb1.insert(END,restitle,hyperlink.add(partial(click1, resurl[0])))