Search code examples
pythonubuntutkintervlcclickable

how to make text clickable in tkinter python on Ubuntu


I am writing a program in python on Ubuntu, to import and print the names of video files from a folder but It is printing as a simple text, not in a click-able form.

I want to make them clickable & open on video player 'vlc' on one click.

Can you plz guide me to do that?

import io,sys,os,subprocess 
from Tkinter import *

def viewFile():
    for f in os.listdir(path):
        if f.endswith(".h264"):
            tex.insert(END,f + "\n")

if __name__ == '__main__':
    root = Tk()

    mainframe= root.title("FILE MANAGER APPLICATION")                         # Program Objective
    mainframe= root.attributes('-fullscreen', True)

    step = LabelFrame(root,text="FILE MANAGER", font = "Arial 20 bold   italic")
    step.grid(row=0, columnspan=7, sticky='W',padx=100, pady=5, ipadx=130, ipady=25)

    Button(step,    text="File View",   font = "Arial 8 bold    italic",    activebackground="turquoise",   width=30, height=5, command=viewFile).grid      (row= 1, column =2)
    Button(step,    text="Exit",        font = "Arial 8 bold    italic",    activebackground="turquoise",   width=20, height=5, command=root.quit).grid     (row= 1, column =5)

    tex = Text(master=root)
    scr=Scrollbar(root,orient =VERTICAL,command=tex.yview)
    scr.grid(row=2, column=2, rowspan=15, columnspan=1, sticky=NS)
    tex.grid(row=2, column=1, sticky=W)
    tex.config(yscrollcommand=scr.set,font=('Arial', 8, 'bold', 'italic'))

    global process
    path = os.path.expanduser("~/python")                   # Define path To play, delete, or rename video
    root.mainloop()

Solution

  • You can add tags to spans of characters in the text widget, and you can set bindings on tags. So, a simple solution is to create a unique tag for each filename, and a unique binding for that tag.

    For example:

    def viewFile():
        for f in os.listdir(path):
            if f.endswith(".h264"):
                linkname="link-" + f
                tex.insert(END,f + "\n", linkname)
                tex.tag_configure(linkname, foreground="blue", underline=True)
                tex.tag_bind(linkname, "<1>", lambda event, filename=f: openFile(filename))
    

    This will cause a function named openFile to be called with one argument, which is the filename. You can then do whatever you want in that function.