Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperlink in Tkinter Text widget?

I am re designing a portion of my current software project, and want to use hyperlinks instead of Buttons. I really didn't want to use a Text widget, but that is all I could find when I googled the subject. Anyway, I found an example of this, but keep getting this error:

TclError: bitmap "blue" not defined

When I add this line of code (using the IDLE)

hyperlink = tkHyperlinkManager.HyperlinkManager(text)

The code for the module is located here and the code for the script is located here

Anyone have any ideas?

The part that is giving problems says foreground="blue", which is known as a color in Tkinter, isn't it?

like image 948
Zac Brown Avatar asked Aug 04 '10 02:08

Zac Brown


2 Answers

If you don't want to use a text widget, you don't need to. An alternative is to use a label and bind mouse clicks to it. Even though it's a label it still responds to events.

For example:

import tkinter as tk

class App:
    def __init__(self, root):
        self.root = root
        for text in ("link1", "link2", "link3"):
            link = tk.Label(text=text, foreground="#0000ff")
            link.bind("<1>", lambda event, text=text: self.click_link(event, text))
            link.pack()

    def click_link(self, event, text):
        print("You clicked '%s'" % text)

root = tk.Tk()
app = App(root)
root.mainloop()

If you want, you can get fancy and add additional bindings for <Enter> and <Leave> events so you can alter the look when the user hovers. And, of course, you can change the font so that the text is underlined if you so choose.

Tk is a wonderful toolkit that gives you the building blocks to do just about whatever you want. You just need to look at the widgets not as a set of pre-made walls and doors but more like a pile of lumbar, bricks and mortar.

like image 126
Bryan Oakley Avatar answered Nov 07 '22 21:11

Bryan Oakley


"blue" should indeed be acceptable (since you're on Windows, Tkinter should use its built-in color names table -- it might be a system misconfiguration on X11, but not on Windows); therefore, this is a puzzling problem (maybe a Tkinter misconfig...?). What happen if you use foreground="#00F" instead, for example? This doesn't explain the problem but might let you work around it, at least...

like image 33
Alex Martelli Avatar answered Nov 07 '22 21:11

Alex Martelli