如何在Ubuntu上的tkinter python中使文本可单击

时间:2015-01-14 19:46:55

标签: python ubuntu tkinter vlc clickable

我在Ubuntu上用python编写程序,从文件夹中导入和打印视频文件的名称,但它是一个简单的文本打印,而不是一个可点击的形式。

我想让它们可点击和放大只需点击一下即可在视频播放器'vlc'上打开。

你可以指导我这样做吗?

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()

3 个答案:

答案 0 :(得分:2)

您可以在文本小部件中为字符跨度添加标记,也可以在标记上设置绑定。因此,一个简单的解决方案是为每个文件名创建一个唯一标记,并为该标记创建唯一的绑定。

例如:

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))

这将导致使用一个参数调用名为openFile的函数,该参数是文件名。然后,您可以在该功能中执行任何操作。

答案 1 :(得分:2)

在最后一行尝试此行以在VLC上打开视频

tex.tag_bind(linkname, "<1>", lambda event, filename =path+'/'+f: subprocess.call(['vlc',filename]))

答案 2 :(得分:0)

一种简单的方法是循环遍历所有文件并为每个文件创建一个按钮,如此

 fram = Frame(root)
 files = os.listdir(path):
 for f in range(0, len(files), 1):
    if files[f].endswith(".h264"):
        name = files[f].split(".")
        b = Button(fram, text=name[0])
        b.bind('<Button>', openV)
        b.grid(row=f, column=1)

现在你的openV功能应该像这样实际打开文件

def openV(event):
     b = event.widget()
     properties = b.config() #get all config for this widget, conveniently the only value right now is text
     n = properties[0]
     bashCommand = "vlc " + n + ".h264" # this is the command to actually be exectuted
     os.system(bashCommand)

确保您的系统上安装了python-swap,否则os.system()会出错 您不需要具有唯一ID,因为同一文件夹中具有相同名称和扩展名的2个文件不可能存在!