写一个python 脚本 能弹出选项框选择输入文件,当输入后下次执行则不弹窗。并且详细解释代码
时间: 2024-03-25 12:38:06 浏览: 65
可以使用Python的tkinter库来实现弹出选项框选择输入文件的功能。具体代码如下:
```python
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = ''
try:
with open('file_path.txt', 'r') as f:
file_path = f.read().strip()
except FileNotFoundError:
pass
if not file_path:
file_path = filedialog.askopenfilename()
with open('file_path.txt', 'w') as f:
f.write(file_path)
print('Selected file:', file_path)
```
首先,我们导入tkinter库,并创建一个root窗口并隐藏它。然后,我们尝试从文件`file_path.txt`中读取之前保存的文件路径,如果该文件不存在,则跳过该步骤。
接下来,我们检查文件路径是否已经存在。如果不存在,我们弹出一个选项框,让用户选择输入文件,并将其保存到`file_path.txt`中。
最后,我们打印所选文件的路径。
通过这种方式,我们可以实现每次执行脚本时只弹出一次选项框,并且下次执行时不会再次弹出选项框。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.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://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)