如何用Python实现显示指定格式文件并双击同窗口打开的窗口程序
Build a Python Desktop App to Browse and View Files in a Specified Folder
Hey there! Let's put together a desktop application that lets you browse .txt, .doc, .docx, and .pdf files in a chosen folder, and view their content right in the same window when you double-click a file. We'll use Tkinter (Python's built-in GUI toolkit) for the interface, plus a few helper libraries to parse different file formats.
Step 1: Install Required Libraries
First, install the packages needed to handle non-txt files:
pip install python-docx PyPDF2
python-docx: Reads .docx files (note: it doesn't support .doc files natively—for .doc, you can usetextract(requires extra system dependencies) orpywin32on Windows to interact with Microsoft Word)PyPDF2: Extracts text from PDF files
Step 2: Full Code Implementation
Here's the complete code with comments explaining each part:
import os import tkinter as tk from tkinter import ttk, scrolledtext, filedialog from docx import Document from PyPDF2 import PdfReader class FileViewerApp: def __init__(self, root): self.root = root self.root.title("Folder File Viewer") self.root.geometry("800x600") # Set up the main layout: left (file list) + right (content view) self.main_frame = ttk.PanedWindow(root, orient=tk.HORIZONTAL) self.main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # Left panel: Folder selection + file list self.left_panel = ttk.Frame(self.main_frame, width=250) self.main_frame.add(self.left_panel) # Folder selection button self.folder_btn = ttk.Button(self.left_panel, text="Select Folder", command=self.select_folder) self.folder_btn.pack(pady=10, fill=tk.X, padx=5) # File list box self.file_list = tk.Listbox(self.left_panel, selectmode=tk.SINGLE) self.file_list.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # Bind double-click event to open file self.file_list.bind("<Double-1>", self.open_selected_file) # Right panel: Content view self.right_panel = ttk.Frame(self.main_frame) self.main_frame.add(self.right_panel) # Scrolled text widget for content display self.content_text = scrolledtext.ScrolledText(self.right_panel, wrap=tk.WORD) self.content_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # Make content read-only self.content_text.config(state=tk.DISABLED) self.current_folder = "" def select_folder(self): """Open a dialog to select a folder and load valid files""" self.current_folder = filedialog.askdirectory(title="Select Folder") if not self.current_folder: return # Clear existing file list self.file_list.delete(0, tk.END) # Filter for supported file types supported_extensions = (".txt", ".doc", ".docx", ".pdf") for filename in os.listdir(self.current_folder): if filename.lower().endswith(supported_extensions): self.file_list.insert(tk.END, filename) def open_selected_file(self, event): """Read and display the content of the selected file""" selected_index = self.file_list.curselection() if not selected_index: return filename = self.file_list.get(selected_index[0]) file_path = os.path.join(self.current_folder, filename) content = "" try: # Handle different file types if filename.lower().endswith(".txt"): with open(file_path, "r", encoding="utf-8", errors="replace") as f: content = f.read() elif filename.lower().endswith(".docx"): doc = Document(file_path) content = "\n".join([para.text for para in doc.paragraphs]) elif filename.lower().endswith(".pdf"): reader = PdfReader(file_path) content = "\n".join([page.extract_text() for page in reader.pages]) elif filename.lower().endswith(".doc"): # Note: This requires pywin32 (Windows only) # Uncomment the code below if you want to support .doc files """ import win32com.client word = win32com.client.Dispatch("Word.Application") word.Visible = False doc = word.Documents.Open(file_path) content = doc.Content.Text doc.Close() word.Quit() """ content = ".doc files require additional setup (see code comments)" except Exception as e: content = f"Error opening file: {str(e)}" # Update the content text widget self.content_text.config(state=tk.NORMAL) self.content_text.delete(1.0, tk.END) self.content_text.insert(tk.END, content) self.content_text.config(state=tk.DISABLED) if __name__ == "__main__": root = tk.Tk() app = FileViewerApp(root) root.mainloop()
Step 3: How It Works
- Folder Selection: Click the "Select Folder" button to choose the directory you want to browse. The app will populate the left list with only the supported file types.
- View Content: Double-click any file in the list, and its content will load in the right-hand scrolled text panel.
- Read-Only Content: The content panel is read-only to prevent accidental edits to the original files.
Notes on .doc Files
If you need to support .doc files (the older Microsoft Word format):
- On Windows, install
pywin32withpip install pywin32, then uncomment the .doc handling code in theopen_selected_filemethod. - On macOS/Linux, you can use
textract(install withpip install textract), but it requires additional system packages (likeantiwordfor .doc files).
That's it! You can tweak the window size, styling, or add more features like search functionality if you want.
内容的提问来源于stack exchange,提问作者vishal prajapati
相关产品推荐
相关产品推荐

