How to use Tkinter to open file in folder using dropdown?

In this tutorial, we'll explore how to use Tkinter to build a simple file viewer that allows users to open files from a specific folder using a dropdown menu. By the end of this tutorial, you'll have a better understanding of Tkinter and how to create interactive file selection interfaces.

What is Tkinter?

Tkinter is the standard GUI toolkit that comes with Python. It provides a set of tools and widgets for creating graphical user interfaces. Tkinter comes pre-installed with Python, so no additional installation is typically required.

Basic File Viewer Implementation

Let's create a basic Tkinter window with the necessary components for our file viewer. The application will include a Text widget to display file content, a button to select a folder, a dropdown menu to select a file, and another button to open the selected file ?

import tkinter as tk
from tkinter import filedialog, messagebox
import os

def open_file():
    """Open and display the selected file content"""
    selected_file = file_var.get()
    if not selected_file or not folder_path:
        messagebox.showwarning("Warning", "Please select a folder and file first!")
        return
    
    file_path = os.path.join(folder_path, selected_file)
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            text.delete(1.0, tk.END)  # Clear previous content
            text.insert(tk.END, content)
    except Exception as e:
        messagebox.showerror("Error", f"Could not open file: {str(e)}")

def update_dropdown():
    """Update dropdown menu with files from selected folder"""
    try:
        file_list = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
        file_var.set(file_list[0] if file_list else "")
        file_menu['menu'].delete(0, 'end')

        for file_name in file_list:
            file_menu['menu'].add_command(label=file_name, command=tk._setit(file_var, file_name))
        
        if not file_list:
            messagebox.showinfo("Info", "No files found in the selected folder!")
    except Exception as e:
        messagebox.showerror("Error", f"Could not read folder: {str(e)}")

def select_folder():
    """Open folder selection dialog"""
    global folder_path
    folder_path = filedialog.askdirectory(title="Select Folder")
    if folder_path:
        folder_label.config(text=f"Selected: {os.path.basename(folder_path)}")
        update_dropdown()

# Initialize variables
folder_path = ""

# Create the main window
root = tk.Tk()
root.title("File Viewer with Dropdown")
root.geometry("600x500")

# Create a variable to store the selected file
file_var = tk.StringVar()

# Folder selection section
folder_frame = tk.Frame(root)
folder_frame.pack(pady=10)

folder_button = tk.Button(folder_frame, text="Select Folder", command=select_folder, 
                         bg="lightblue", font=("Arial", 10))
folder_button.pack(side=tk.LEFT)

folder_label = tk.Label(folder_frame, text="No folder selected", fg="gray")
folder_label.pack(side=tk.LEFT, padx=10)

# File selection section
file_frame = tk.Frame(root)
file_frame.pack(pady=10)

tk.Label(file_frame, text="Select File:", font=("Arial", 10)).pack(side=tk.LEFT)
file_menu = tk.OptionMenu(file_frame, file_var, "")
file_menu.pack(side=tk.LEFT, padx=10)

open_button = tk.Button(file_frame, text="Open File", command=open_file, 
                       bg="lightgreen", font=("Arial", 10))
open_button.pack(side=tk.LEFT, padx=10)

# Text widget to display file content
text_frame = tk.Frame(root)
text_frame.pack(pady=10, fill="both", expand=True)

text = tk.Text(text_frame, wrap="word", font=("Consolas", 10))
scrollbar = tk.Scrollbar(text_frame, orient="vertical", command=text.yview)
text.configure(yscrollcommand=scrollbar.set)

text.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

# Run the Tkinter event loop
root.mainloop()

How the Application Works

The application consists of several key components that work together to provide file browsing functionality:

Core Functions

  • select_folder() Opens a directory selection dialog and updates the dropdown with files from the chosen folder

  • update_dropdown() Populates the dropdown menu with files from the selected directory, filtering out subdirectories

  • open_file() Reads and displays the content of the selected file in the text widget

User Interface Components

  • Folder Selection Button and label to choose and display the current folder

  • File Dropdown OptionMenu widget populated with files from the selected folder

  • Text Display Text widget with scrollbar to show file contents

Enhanced Features

This improved version includes several enhancements over a basic implementation:

  • Error Handling Try-catch blocks to handle file reading errors and empty folders

  • File Filtering Only displays files (not directories) in the dropdown menu

  • User Feedback Status messages and warnings using messagebox

  • Better Layout Organized using frames and improved visual styling

  • Scrollable Text Added scrollbar for viewing large files

Conclusion

This Tkinter file viewer demonstrates how to create an interactive GUI application that combines folder selection, dropdown menus, and file display functionality. The application provides a solid foundation for more advanced file management tools and showcases essential Tkinter widgets and event handling techniques.

Updated on: 2026-03-27T16:33:28+05:30

777 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements