以下是一个简单的Python GUI程序,包含一个按钮和一个输入框。点击按钮后可以选择txt文档并读取其中的内容。
```python
import tkinter as tk
from tkinter import filedialog
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.select_file_button = tk.Button(self)
self.select_file_button["text"] = "Select File"
self.select_file_button["command"] = self.select_file
self.select_file_button.pack(side="top")
self.file_path_entry = tk.Entry(self)
self.file_path_entry.pack(side="top")
def select_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Text Files", "*.txt")])
self.file_path_entry.delete(0, tk.END)
self.file_path_entry.insert(0, file_path)
with open(file_path, "r") as f:
content = f.read()
print(content)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
```
运行程序后,会显示一个窗口,里面有一个“Select File”按钮和一个输入框。点击按钮后会弹出文件选择对话框,选择一个txt文件后,文件路径会显示在输入框中,并且文件内容会被打印到控制台中。