利用tkinter从文件中读入专业数据
时间: 2023-03-20 11:06:14 浏览: 241
可以使用Python的内置模块tkinter来实现从文件中读入专业数据。具体步骤如下:
1. 导入tkinter模块和文件读取模块
```python
import tkinter as tk
from tkinter import filedialog
import csv
```
2. 创建一个窗口并添加一个按钮,点击按钮后弹出文件选择对话框
```python
root = tk.Tk()
def open_file():
file_path = filedialog.askopenfilename()
read_file(file_path)
button = tk.Button(root, text="选择文件", command=open_file)
button.pack()
root.mainloop()
```
3. 编写读取文件的函数,将读取的数据存储到一个列表中
```python
def read_file(file_path):
data = []
with open(file_path, 'r') as f:
reader = csv.reader(f)
for row in reader:
data.append(row)
print(data)
```
4. 将读取到的数据展示在窗口中,可以使用tkinter的Text组件
```python
text = tk.Text(root)
text.pack()
def read_file(file_path):
data = []
with open(file_path, 'r') as f:
reader = csv.reader(f)
for row in reader:
data.append(row)
for row in data:
text.insert(tk.END, row)
text.insert(tk.END, '\n')
```
完整代码如下:
```python
import tkinter as tk
from tkinter import filedialog
import csv
root = tk.Tk()
def open_file():
file_path = filedialog.askopenfilename()
read_file(file_path)
button = tk.Button(root, text="选择文件", command=open_file)
button.pack()
text = tk.Text(root)
text.pack()
def read_file(file_path):
data = []
with open(file_path, 'r') as f:
reader = csv.reader(f)
for row in reader:
data.append(row)
for row in data:
text.insert(tk.END, row)
text.insert(tk.END, '\n')
root.mainloop()
```
阅读全文