tkinter导入文本按钮
时间: 2023-09-13 22:03:30 浏览: 79
可以使用Tkinter的`filedialog`模块来实现导入文本的功能,具体步骤如下:
1. 导入`Tkinter`和`filedialog`模块:
```python
from tkinter import *
from tkinter import filedialog
```
2. 创建一个Tkinter窗口并添加"导入文本"按钮:
```python
root = Tk()
def open_file(): # 定义打开文件函数
file_path = filedialog.askopenfilename() # 打开文件对话框
with open(file_path, 'r') as file: # 打开文件
text = file.read() # 读取文件内容
# 在文本框中显示文件内容
text_box.delete('1.0', END) # 清空文本框
text_box.insert(END, text) # 在文本框中插入文件内容
import_button = Button(root, text="导入文本", command=open_file)
import_button.pack()
```
3. 创建一个文本框用于显示导入的文本内容:
```python
text_box = Text(root)
text_box.pack()
```
完整代码如下:
```python
from tkinter import *
from tkinter import filedialog
root = Tk()
def open_file():
file_path = filedialog.askopenfilename()
with open(file_path, 'r') as file:
text = file.read()
text_box.delete('1.0', END)
text_box.insert(END, text)
import_button = Button(root, text="导入文本", command=open_file)
import_button.pack()
text_box = Text(root)
text_box.pack()
root.mainloop()
```
阅读全文
相关推荐


















