python - python tkinter 中的菜单 : save file to a new directory

标签 python file tkinter

我的 python tkinter GUI 程序在执行一些操作后正在写入一个文本文件。我想添加一个导出菜单,以便用户可以将此文件保存到 U 盘或其他目录中。 (我知道我们可以进行正常的复制粘贴)。但我想添加这个导出菜单。我想要实现的是,当用户单击此导出菜单时,应打开当前目录,并且用户可以选择文件(已创建并存在于当前目录中的 myData.txt),并且用户现在可以选择一个新目录并将 myData.txt 保存在新目录中。 (它应该也可以在Linux平台上运行)

#My gui app creates a text file myData.txt in my current folder when I run the program. 

from tkinter import *
from tkinter import messagebox
import sys

def Export_File():
    #what do i need here???


windows = Tk()
menubar = Menu(windows)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Export", command =Export_File )

filemenu.add_command(label="Exit", command=Exit_File)
menubar.add_cascade(label="File", menu=filemenu)
windows.configure(menu=menubar)


windows.mainloop()

最佳答案

首先,您还需要导入 2 个东西

import os
from tkinter import filedialog

接下来,将变量分配给用户选择的目录,并使用 os 模块更改到该目录

def Export_File():
    dir_name = filedialog.askdirectory() # asks user to choose a directory
    os.chdir(dir_name) # changes your current directory

要检查当前目录,您可以随时

curr_directory = os.getcwd()
print(curr_directory)

关于python - python tkinter 中的菜单 : save file to a new directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57005902/

相关文章:

javascript - HTML5 FileWriter 无效状态错误

database - 将平台配置存储在数据库或文件中更好吗?

python - “wait_window”方法有什么作用?

python - 有什么方法可以在 python 中为 hashlib 使用非 openssl md5?

python - 在 matplotlib 上抓取并绘制由线段交叉的二维数组的值

Python 服务器端 AJAX 库?

android - 选择文件对话框

python - python turtle 可以采样背景颜色吗?

python - 无法更新标签文本

python - 根据条件将值应用于数字的所有实例