2011-08-17 16 views
6

मैं 'फ़ाइल को सहेजने' संवाद पेश करने के लिए एक पायथन फ़ंक्शन ढूंढने का प्रयास कर रहा हूं जो एक फ़ाइल नाम को एक स्ट्रिंग के रूप में लौटाता है।पायथन सेवए संवाद का उपयोग कैसे करें

मुझे जल्दी से tkFileDialog मॉड्यूल मिला, केवल यह समझने के लिए कि asksaveasfilename फ़ंक्शन एक अपवाद फेंकता है यदि फ़ाइल दर्ज की गई है, जो पहले से मौजूद नहीं है, जो व्यवहार मैं नहीं ढूंढ रहा हूं।

मुझे लगता है कि मैं जो जवाब ढूंढ रहा हूं वह पाइथन FileDialog मॉड्यूल में है, लेकिन मेरा सबसे अच्छा अनुमान यह है कि SaveFileDialog वर्ग की विधि है।

>>> FileDialog.SaveFileDialog.get_selection() 
Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
TypeError: unbound method get_selection() must be called with SaveFileDialog instance as first argument (got nothing instead) 
>>> x = FileDialog.SaveFileDialog() 
Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
TypeError: __init__() takes at least 2 arguments (1 given) 

सबसे पहले मैं अगर मैं सिर्फ संवाद बॉक्स आह्वान सकता देखने के लिए कोशिश कर रहा था: नीचे, आप मेरी उपयोग पता लगाने की कोशिश इंटरैक्टिव मोड में के बारे में स्खलित देख सकते हैं। फिर यह देखते हुए कि मुझे SaveFileDialog उदाहरण की आवश्यकता है, मैंने चर को x पर असाइन करने का प्रयास किया। लेकिन जाहिर है कि दो तर्क भी लेते हैं, और यही वह जगह है जहां मैं वास्तव में खो जाता हूं।

सहायता?

उत्तर

7

यहां asksaveasfilename() फ़ंक्शन के लिए एक छोटा सा उदाहरण है। मुझे उम्मीद है कि आप इसका उपयोग कर सकते हैं:

import Tkinter, Tkconstants, tkFileDialog 

class TkFileDialogExample(Tkinter.Frame): 

    def __init__(self, root): 

     Tkinter.Frame.__init__(self, root) 
     button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5} 
     Tkinter.Button(self, text='asksaveasfilename', command=self.asksaveasfilename).pack(**button_opt) 

     self.file_opt = options = {} 
     options['filetypes'] = [('all files', '.*'), ('text files', '.txt')] 
     options['initialfile'] = 'myfile.txt' 
     options['parent'] = root 

    def asksaveasfilename(self): 
     filename = tkFileDialog.asksaveasfilename(**self.file_opt) 

     if filename: 
      return open(filename, 'w') 

if __name__=='__main__': 
    root = Tkinter.Tk() 
    TkFileDialogExample(root).pack() 
    root.mainloop() 

मैं मौजूदा फाइलों को खोलने (और बनाने) में सक्षम था।

संबंधित मुद्दे