[파이썬] tkinter 파일 대화 상자 (`filedialog`)

Working with files is a common task in many software applications. In Python, tkinter is a popular library for creating graphical user interfaces (GUI), and it provides a convenient way to create file dialog boxes using the filedialog module.

Introduction to filedialog

The filedialog module in tkinter allows you to open file dialog boxes that enable users to select or save files. These dialog boxes provide a user-friendly interface for interacting with file systems and selecting files or saving files to a specific location.

You can use filedialog to:

Example Usage

Here’s an example that demonstrates how to use tkinter’s filedialog module to open a file dialog box and retrieve the selected file path:

import tkinter as tk
from tkinter import filedialog

def open_file_dialog():
    file_path = filedialog.askopenfilename()
    if file_path:
        # Perform further actions on the selected file
        print("Selected File:", file_path)

# Create a tkinter window
window = tk.Tk()

# Add a button to open the file dialog box
open_button = tk.Button(window, text="Open File", command=open_file_dialog)
open_button.pack()

# Run the tkinter event loop
window.mainloop()

In the above example, we import the necessary modules, define a function open_file_dialog(), and create a tkinter window.

The open_file_dialog() function is associated with a button click event. When the button is clicked, the file dialog box is opened using the askopenfilename() method. The selected file path is printed to the console if a file is chosen.

Conclusion

The filedialog module in tkinter provides a simple and effective way to incorporate file dialog boxes into your Python applications. Whether you need to open or save files, select directories, or multiple files, filedialog offers a clean and user-friendly solution.

By using the examples and information provided in this blog post, you can easily implement file dialog boxes in your tkinter applications and enhance the file handling capabilities of your software.