'Tkinter - way to open a directory window in Windows Explorer

I've been looking into Tkinter and recently have made a small program just to monitor folders and check how many files are inside.

I'de like to create buttons that open the folders in Windows Explorer but I can't find any info on doing so.

Anyone got any Ideas?

Cheers, Jon

Thanks for the quick response I'd already tried something similar but I'm probably doing something wrong. Here's my code :

def open():
    os.system("explorer C:\\ folder dir")

label1 = Button(self, text="Pre TC", fg="red", font=("Ariel", 9, "bold"), command=open)


Solution 1:[1]

self has to be used when you are calling a function defined under the same class name of which label1 or button1 is an object. Otherwise you get the Tkinter callback exception as the function is not found.

That is why renaming open to self.open works

Solution 2:[2]

Thanks everyone for your help it was a combo of your answers that helped with this one!

Still not 100% on why what I did worked but I added self as the argument to open() so open(self) and added as the command self.open. So the edited code from my question looks like this:

def open(self):
    os.system("start C:/folder dir/")

button1= Button(self, text="Pre TC", fg="red", font=("Ariel", 9, "bold"), command=self.open)

(Also changed the name of the button)

If anyone knows why the self argument has to be there or can point me in the direction of more info that would be greatly appreciated.

Cheers! Jon

Solution 3:[3]

You can use a terminal command to do this and make a button to call this function. Exemple in Windows:

from tkinter import *       
from tkinter.ttk import *
import os
 
# opening any folder 
def openFolder():
    path='C:'
    command = 'explorer.exe ' + path
    os.system(command)

root = Tk()         
root.geometry('100x100')    
btn = Button(root, text = 'Click me !',command = openFolder)
btn.pack(side = 'top')    
root.mainloop()

Others interesting terminal commands:

import os

# opening files
file = 'test.md'
command = 'start ' + file
os.system(command)

# opening current folder 
command = 'explorer.exe .'
os.system(command)

# opening any folder 
path='C:'
command = 'explorer.exe ' + path
os.system(command)

Using Commands

Solution 4:[4]

You cannot use the command option on a Label item. Try making that a button, and it should work!

Solution 5:[5]

One thing I noticed is that the path is sensitive to the slash or backslash. "C:/folder" does not work with os.system. It just starts in some default Documents folder. "C:\folder" works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nihal111
Solution 2 Jon.H
Solution 3
Solution 4 nihal111
Solution 5 Andy