Python:根据用户输入保存文件

时间:2016-03-22 01:24:14

标签: python windows python-3.x tkinter pickle

我试图通过'另存为'来保存python tkinter窗口中的文件。提示。我已经看了一会儿,似乎无法找到我想要的答案。我可以使用默认名称将信息成功保存到文件中,甚至可以使用用户通过input()输入的名称保存它,但是,这不是我想要做的。我希望用户能够点击,另存为'然后当提示出现时,他们输入文件名并保存为该名称,我似乎无法在任何地方找到答案。这是我的代码:

# Import Tkinter
from tkinter import *
import os
import pickle
from tkinter.filedialog import askopenfilename, asksaveasfile
from tkinter.messagebox import *

MainWindow = Tk()
MainWindow.geometry("600x400")
MainWindow.attributes("-alpha", 1)
MainWindow.title(string="Hours Log")
CurrentDirect=os.getcwd()

def FileSaveAs():
fname = asksaveasfile(initialdir=CurrentDirect ,filetypes=(("Text Files", "*.txt"),
                                       ("All files", "*.*") ))
if fname:
        try:
            print(fname)
            SH = SHVar.get()
            SM = SMVar.get()
            SAP = SAPVar.get()
            EH = EHVar.get()
            EM = EMVar.get()
            EAP = EAPVar.get()
            DM = DMVar.get()
            DD = DDVar.get()
            DY = DYVar.get()
            DE = Description.get("1.0", END)
            AP = APVar.get()
            with open("filename.txt", 'wb') as f:
                pickle.dump([SH, SM, SAP, EH, EM, EAP, DM, DD, DY, DE, AP], f)

        except:
            showerror("FILE SAVE ERROR", "Error on Saving File!\n'%s'" % fname)
        return

我理解" filename.txt"是要保存的文件的名称,但是,如何从提示符中获取变量名称?

注意:此代码中没有错误,它可以与我的程序的其余部分一起运行。

1 个答案:

答案 0 :(得分:1)

您可以使用asksaveasfile代替fname"filename.txt"代替 60 def asksaveasfile(self): 61 62 """Returns an opened file in write mode.""" 63 64 return tkFileDialog.asksaveasfile(mode='w', **self.file_opt) 65 66 def asksaveasfilename(self): 67 68 """Returns an opened file in write mode. 69 This time the dialog just returns a filename and the file is opened by your own code. 70 """

table_one

+------+-------------+
| id   | cool        |
+------+-------------+
| 1    | 1.58        |
| 2    | 8.88        |
+------+-------------+

table_two

+------+-------------+
| id   | okies       |
+------+-------------+
| 1    | 2.15        |
| 2    | 7.50        |
+------+-------------+

table_result

+------+-------------------+
| id   | result            |
+------+-------------------+
| 1    | 1.58 (min value)  |
| 2    | 7.50 (min value)  |
+------+-------------------+