단순 대화상자로 Python에서 파일 선택
저는 파이썬 콘솔 애플리케이션에서 파일 경로를 입력으로 받고 싶습니다.
현재 콘솔에서 입력으로 전체 경로만 요청할 수 있습니다.
사용자가 전체 경로를 입력하는 대신 파일을 선택할 수 있는 간단한 사용자 인터페이스를 트리거하는 방법이 있습니까?
Tkinter를 사용하는 것은 어떻습니까?
from Tkinter import Tk # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)
알았어!
완벽성을 위한 Etaoin의 답변은 Python 3.x 버전입니다.
from tkinter.filedialog import askopenfilename
filename = askopenfilename()
EasyGui 사용:
import easygui
print(easygui.fileopenbox())
설치 방법:
pip install easygui
데모:
import easygui
easygui.egdemo()
Python 2에서는tkFileDialog모듈.
import tkFileDialog
tkFileDialog.askopenfilename()
Python 3에서는tkinter.filedialog모듈.
import tkinter.filedialog
tkinter.filedialog.askopenfilename()
이것은 나에게 효과가 있었습니다.
참조: https://www.youtube.com/watch?v=H71ts4XxWYU
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename()
print(file_path)
고려해야 할 또 다른 옵션은 Zenity: http://freecode.com/projects/zenity 입니다.
저는 Python 서버 애플리케이션(GUI 구성 요소 없음)을 개발하고 있었기 때문에 Python GUI 툴킷에 종속성을 도입하고 싶지 않았지만, 디버그 스크립트 중 일부를 입력 파일로 매개 변수화하고 명령줄에 파일을 지정하지 않은 경우 사용자에게 시각적으로 파일을 요청하고 싶었습니다.제니스는 완벽하게 어울렸습니다.이렇게 하려면 하위 프로세스 모듈을 사용하여 "zenity --file-selection"을 호출하고 stdout을 캡처합니다.물론 이 솔루션은 Python에만 국한된 것은 아닙니다.
Zenity는 여러 플랫폼을 지원하며 개발 서버에 이미 설치되어 있어 원치 않는 종속성을 도입하지 않고 디버깅/개발을 용이하게 했습니다.
나중에 중복되는 질문에 대한 다음 답변에서 제안한 바와 같이, wxPython에서 tkinter보다 훨씬 더 나은 결과를 얻었습니다.
https://stackoverflow.com/a/9319832
wxPython 버전은 xfce 데스크톱이 있는 OpenSUSE Tumblweed 설치의 다른 응용 프로그램에서 열린 파일 대화 상자와 동일하게 보이는 파일 대화 상자를 생성한 반면, tkinter는 익숙하지 않은 측면 스크롤 인터페이스로 비좁고 읽기 어려운 것을 생성했습니다.
제안된root.withdraw()(여기서도) 창을 삭제하는 대신 숨깁니다. VS Code에서 대화형 콘솔을 사용할 때 문제가 발생했습니다("중복 실행" 오류).
다음은 "열기" 또는 "다른 이름으로 저장"(Windows의 경우 python 3)에서 파일 경로를 반환하는 두 개의 스니펫입니다.
import tkinter as tk
from tkinter import filedialog
filetypes = (
('Text files', '*.TXT'),
('All files', '*.*'),
)
# open-file dialog
root = tk.Tk()
filename = tk.filedialog.askopenfilename(
title='Select a file...',
filetypes=filetypes,
)
root.destroy()
print(filename)
# save-as dialog
root = tk.Tk()
filename = tk.filedialog.asksaveasfilename(
title='Save as...',
filetypes=filetypes,
defaultextension='.txt'
)
root.destroy()
print(filename)
# filename == 'path/to/myfilename.txt' if you type 'myfilename'
# filename == 'path/to/myfilename.abc' if you type 'myfilename.abc'
Player를 사용하면 Windows, macOS, Linux 및 Android에서 기본 파일 선택기를 사용할 수 있습니다.
import plyer
plyer.filechooser.open_file()
두 방법이 .choose_dir그리고.save_file자세한 내용은 여기 문서를 참조하십시오.
터미널 창에서 파일 선택기를 바로 보여주는 간단한 기능이 있습니다.이 방법은 여러 파일 또는 디렉터리 선택을 지원합니다.이는 GUI가 지원되지 않는 환경에서도 실행할 수 있는 추가적인 이점이 있습니다.
from os.path import join,isdir
from pathlib import Path
from enquiries import choose,confirm
def dir_chooser(c_dir=getcwd(),selected_dirs=None,multiple=True) :
'''
This function shows a file chooser to select single or
multiple directories.
'''
selected_dirs = selected_dirs if selected_dirs else set([])
dirs = { item for item in listdir(c_dir) if isdir(join(c_dir, item)) }
dirs = { item for item in dirs if join(c_dir,item) not in selected_dirs and item[0] != "." } # Remove item[0] != "." if you want to show hidde
options = [ "Select This directory" ]
options.extend(dirs)
options.append("⬅")
info = f"You have selected : \n {','.join(selected_dirs)} \n" if len(selected_dirs) > 0 else "\n"
choise = choose(f"{info}You are in {c_dir}", options)
if choise == options[0] :
selected_dirs.add(c_dir)
if multiple and confirm("Do you want to select more folders?") :
return get_folders(Path(c_dir).parent,selected_dirs,multiple)
return selected_dirs
if choise == options[-1] :
return get_folders(Path(c_dir).parent,selected_dirs,multiple)
return get_folders(join(c_dir,choise),selected_dirs,multiple)
문의 사항을 설치하려면,
파이프 설치 문의
관련된 모든 문제를 해결했습니다.from tkinter import * from tkinter import filedialog
Pycharm IDE에서 비주얼 스튜디오 코드 IDE로 마이그레이션하는 것만으로 모든 문제가 해결됩니다.
언급URL : https://stackoverflow.com/questions/3579568/choosing-a-file-in-python-with-simple-dialog
'codememo' 카테고리의 다른 글
| ( )=>반응의 차이는 무엇입니까?FC 및 ( )=>JSX.요소 (0) | 2023.06.17 |
|---|---|
| Python에서 매우 큰 수를 처리합니다. (0) | 2023.06.17 |
| TokenRefresh()의 Firebase가 호출되지 않았습니다. (0) | 2023.06.17 |
| 상대 경로(리팩터링 메서드)에서 절대 URL 가져오기 (0) | 2023.06.17 |
| 오라클의 'yyy' 날짜 마스크와 'rr' 날짜 마스크의 차이점은 무엇입니까? (0) | 2023.06.17 |