1

I am making a file browser in Python 3.5 and I've included renaming and viewing, but am not sure how to make it so that when you click the file it opens. I know how to use os.startfile("file"), but I'm not sure where to include it.

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

from idlelib.TreeWidget import ScrolledCanvas, FileTreeItem, TreeNode

root = Tk()
root.title("Browser")
sc = ScrolledCanvas(root, bg="white", highlightthickness=0, takefocus=1)
sc.frame.pack(expand=1, fill="both", side="left")
loc = input("Please enter your directory: ")
item = FileTreeItem(loc)
node = TreeNode(sc.canvas, None, item)
node.expand()
root.mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

You can get the filename associated with the TreeNode by subclassing idlelib.TreeNode and overriding the inherited select() method.

Here's an example of what I mean:

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

from idlelib.TreeWidget import ScrolledCanvas, FileTreeItem, TreeNode

class MyTreeNode(TreeNode):
    def select(self, event=None):
        TreeNode.select(self, event)  # can't use super() here in Python 2
        print('select called')
        print('self.item.GetText(): {!r}'.format(self.item.GetText()))
        print('self.item.path: "{}"'.format(self.item.path))  # call os.startfile() here

root = Tk()
root.title("Browser")

sc = ScrolledCanvas(root, bg="white", highlightthickness=0, takefocus=1)
sc.frame.pack(expand=1, fill="both", side="left")

loc = input("Please enter your directory: ")
item = FileTreeItem(loc)

node = MyTreeNode(sc.canvas, None, item)
node.expand()

root.mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Do you know how to get the whole directory name instead of just the file name eg "C:/windows/system32/calc.exe" instead of just "calc.exe" ? – Luke Timmons May 29 '17 at 18:51
  • Luke: Regarding your follow-on question—not knowing the full path was one of the reason's I just printed out the text associated with the `TreeNode` instead of calling `os.startfile()`. I'll look into possible solutions and let you know if I find one. – martineau May 29 '17 at 19:18
  • I've tried adding the the name togther with the input entered by the user `(loc + self.item.get())` but it doesn't work for the subfolders and when you try and get a file from them. – Luke Timmons May 29 '17 at 19:23
  • Luke: It looks like that instead of using `self.item.GetText()` to get the filename, you could use `self.item.path` to get a full path to the file. – martineau May 29 '17 at 19:41