Home > Blockchain >  open KNOWNFOLDERID with askopenfilename in Tkinter / Python
open KNOWNFOLDERID with askopenfilename in Tkinter / Python

Time:08-12

I want to set my initialdir to a KNOWNFOLDERID like Documents or Desktop. Is this even possible? I tried like this, but instead it open up the directory of my python project.

from tkinter import *
from tkinter import filedialog

root = Tk()

root.filename = filedialog.askopenfilename(
    initialdir="%USERPROFILE%/Documents",
    title="get a file",
    filetypes=((".jpg files", "*.jpg"), (".png files", "*.png")) 
)

root.mainloop()

CodePudding user response:

You can use pathlib's home if you just need the user's directory.

To get the path of the documents folder use

from pathlib import Path

docs_folder = Path.home() / "Documents"

This will work both on Windows and Unix based OS.

Alternatively you can use expandvars from os.path

import os
docs_folder = os.path.join(os.path.expandvars('%USERPROFILE%'),'Documents')
  • Related