编一段python程序,gui界面中,选择一个文件夹,并把文件夹中txt文件全部在窗口中列出来
时间: 2024-03-25 09:39:44 浏览: 54
好的,以下是一个简单的Python程序,使用tkinter库创建了一个GUI界面,可以选择文件夹,并将文件夹中所有的txt文件列出来:
```python
import tkinter as tk
from tkinter import filedialog
import os
root = tk.Tk()
root.withdraw()
def select_folder():
folder_path = filedialog.askdirectory()
txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]
show_files(txt_files)
def show_files(files):
file_window = tk.Toplevel(root)
file_window.title("TXT Files")
file_window.geometry("300x300")
file_listbox = tk.Listbox(file_window)
for file in files:
file_listbox.insert(tk.END, file)
file_listbox.pack(fill=tk.BOTH, expand=True)
select_folder()
```
在这个程序中,我们首先导入了tkinter库和os库。然后创建了一个隐藏的tkinter窗口`root`。接着定义了一个`select_folder`函数,用于弹出选择文件夹的对话框,并筛选出文件夹中所有的txt文件。然后调用`show_files`函数,将txt文件列表传递进去。
在`show_files`函数中,我们创建了一个新的窗口`file_window`,并设置了窗口标题和大小。然后创建了一个`Listbox`组件`file_listbox`,用于显示txt文件列表。使用一个循环将所有的txt文件添加到`file_listbox`中。最后调用`pack`函数将`file_listbox`组件添加到`file_window`窗口中,并设置fill和expand参数为True,以使组件随窗口大小自动调整。
最后,我们调用`select_folder`函数,运行程序时将弹出选择文件夹的对话框,并以列表形式显示txt文件。
阅读全文
相关推荐
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)