[Python] Is there a way to implement anchor links in HtmlFrame from tkinter?

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    am building a Markdown viewer using tkinterweb.HtmlFrame, where I need to handle both internal anchor links (like #introduction) and external URLs (like https://www.google.com). The problem I'm facing is:

    Internal Links (#id): When I click an internal link (e.g., <a href="#introduction">Introduction</a>), it's treated like a normal URL (e.g., file:///C:/path/#introduction), which causes issues in scrolling to the section.
    External Links (http://): External URLs open correctly in a web browser, but internal links are not being processed to scroll to the section they point to within the HtmlFrame.


    I am using the open_link(url) function to process all link clicks. My current approach to detect and handle internal vs external links involves using webbrowser.open() for external links, but internal links (#id) don't behave as expected—they are treated as file URLs instead of navigating to the corresponding section inside the HtmlFrame. What I Want to Achieve:

    When an internal link (e.g., #introduction) is clicked, the viewer should scroll to the appropriate section inside the HtmlFrame without opening a new URL or file.
    When an external URL (e.g., https://www.google.com) is clicked, it should open in the default web browser.


    Current Code:

    def open_link(url): if url.startswith("#"):
    html_frame.load_html(html_content) # Reload to keep content html_frame.tk.call("eval", f"document.getElementById('{url[1:]}').scrollIntoView();") # Scroll to the section elif url.startswith("file:///") and "#" in url:
    section_id = url.split("#")[-1] html_frame.load_html(html_content) html_frame.tk.call("eval", f"document.getElementById('{section_id}').scrollIntoView();") else: webbrowser.open(url)

    However, I get issues with internal links being treated as file URLs, and the scroll functionality doesn't seem to work. What I've Tried:

    Used html_frame.load_html(html_content) to reload the page and then scroll to the element.
    Attempted using tk.call("eval", f"document.getElementById('{section_id}').scrollIntoView();") to trigger scrolling, but this doesn't seem to work with tkinterweb.



    How can I properly handle internal anchor links (#id) in tkinterweb.HtmlFrame to scroll to the section instead of treating it as a file URL?
    Is there a way to differentiate between internal links and external URLs and handle them correctly in tkinterweb?

    Continue reading...

Compartilhe esta Página