编一段python程序,gui界面中,选择一个文本文件,并把文件的内容在窗口中显示出来,可以编辑
时间: 2024-03-25 08:39:47 浏览: 44
好的,以下是一个简单的Python程序,使用tkinter库创建了一个GUI界面,可以选择文本文件,并将文件的内容在窗口中显示出来,并且可以编辑:
```python
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
def select_file():
file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
with open(file_path, 'r') as f:
contents = f.read()
show_contents(contents, file_path)
def show_contents(contents, file_path):
content_window = tk.Toplevel(root)
content_window.title(file_path)
content_window.geometry("500x500")
content_text = tk.Text(content_window)
content_text.insert(tk.END, contents)
content_text.pack(fill=tk.BOTH, expand=True)
save_button = tk.Button(content_window, text="Save", command=lambda: save_contents(content_text, file_path))
save_button.pack(side=tk.BOTTOM)
def save_contents(content_text, file_path):
contents = content_text.get("1.0", tk.END)
with open(file_path, 'w') as f:
f.write(contents)
select_file()
```
首先我们导入了tkinter库和filedialog模块,然后创建了一个隐藏的tkinter窗口`root`,并定义了`select_file`函数,用于弹出选择文件对话框并读取文件内容。在`select_file`函数中,我们使用`filedialog.askopenfilename`函数弹出选择文件对话框,并筛选出txt文件。然后使用`with open(file_path, 'r') as f:`语句打开文件并读取文件内容。最后调用`show_contents`函数,将文件内容和文件路径传递进去。
在`show_contents`函数中,我们创建了一个新的窗口`content_window`,并设置窗口标题和大小。然后创建了一个`Text`组件`content_text`,用于显示文件内容,并将文件内容插入到组件中。使用`pack`函数将`content_text`组件添加到`content_window`窗口中,并设置fill和expand参数为True,以使组件随窗口大小自动调整。最后创建了一个`Button`组件`save_button`,用于保存文件内容。使用`pack`函数将`save_button`组件添加到`content_window`窗口中,并设置side参数为BOTTOM,以使组件位于窗口底部。我们使用`lambda`表达式将`save_contents`函数和`content_text`组件传递给`save_button`组件,以便在用户单击保存按钮时调用`save_contents`函数。
在`save_contents`函数中,我们使用`get`方法从`content_text`组件中获取用户编辑后的文件内容,并使用`with open(file_path, 'w') as f:`语句将内容写入文件中。
最后,我们调用`select_file`函数,运行程序时将弹出选择文件对话框,并以文本框形式显示文件内容,用户可以编辑并保存文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)