0

Why google.com opens (the last url) if I click on example.com? Here is my code:

import tkinter as tk
import webbrowser

window = tk.Tk()

output = tk.Text(window)
output.pack()

def update_output(new_text):
    output.insert(tk.END, new_text)
    if "://www." in new_text:
        output.tag_add("link", output.index("end-1c linestart"), output.index("end-1c"))
        output.tag_config("link", foreground="blue", underline=1)
        output.tag_bind("link", "<Button-1>", lambda event, url=new_text: webbrowser.open(url))

update_output("https://www.example.com")
update_output("\n")
update_output("https://www.google.com")
update_output("\n")

window.mainloop()

Python version is: 3.9.13

Any help is appreciated!

I also tried to modify the binding to: output.tag_bind("link", "<Button-1>", lambda event: webbrowser.open(new_text))

But the result is the same.

1 Answers1

-1

The problem is that when you click on a link in the text widget, it always opens the last link that was added to the widget. This happens because the code uses the same variable for all the links. To fix this, we need to make sure that each link has its own variable, so that when you click on a link it knowns which link to open. This is done by creating a new variable for each link and passing it to the function that opens the link in the web browser.

import tkinter as tk
import webbrowser

window = tk.Tk()

output = tk.Text(window)
output.pack()

def update_output(new_text):
    output.insert(tk.END, new_text)
    if "://www." in new_text:
        url = new_text
        output.tag_add("link", output.index("end-1c linestart"), output.index("end-1c"))
        output.tag_config("link", foreground="blue", underline=1)
        output.tag_bind("link", "<Button-1>", lambda event, url=url: webbrowser.open(url))

update_output("https://www.example.com")
update_output("\n")
update_output("https://www.google.com")
update_output("\n")

window.mainloop()
  • Your example doesn't work. A tag can only be bound once, so each time you call `tag_bind` you remove the old binding and add a new. It's a solvable problem, but as written, your example exhibits the same problem as the OP. – Bryan Oakley Apr 18 '23 at 21:42