2017-07-27 54 views
0

我有一個代碼問題,從這個帖子 filedialog, tkinter and opening files的FileDialog到一個文件夾中打開文件(Tkinter的)

我想落實到自己的代碼本,但是當我運行這個(沒有我的代碼,只需將代碼你會看到)所有顯示的文件夾都是空的,我實際上不能打開任何東西。

from tkinter import * 
from tkinter.filedialog import askopenfilename 
from tkinter.messagebox import showerror 

class MyFrame(Frame): 
    def __init__(self): 
     Frame.__init__(self) 
     self.master.title("Example") 
     self.master.rowconfigure(5, weight=1) 
     self.master.columnconfigure(5, weight=1) 
     self.grid(sticky=W+E+N+S) 

     self.button = Button(self, text="Browse", command=self.load_file, width=10) 
     self.button.grid(row=1, column=0, sticky=W) 

    def load_file(self): 
     fname = askopenfilename(filetypes=(("Template files", "*.tplate"), 
              ("HTML files", "*.html;*.htm"), 
              ("Python file", "*.py"), 
              ("All files", "*.*"))) 
     if fname: 
      try: 
       print("""here it comes: self.settings["template"].set(fname)""") 
      except:      # <- naked except is a bad idea 
       showerror("Open Source File", "Failed to read file\n'%s'" % fname) 
      return 


if __name__ == "__main__": 
    MyFrame().mainloop() 
+3

是否在打開的對話框中選擇了「所有文件」?將它放在'filetypes'列表的開頭,使其成爲默認值。 – zwer

+0

謝謝!放置'所有文件'在開始解決問題。 @zwer –

回答

1

您的代碼運行良好,我假設您想了解的是如何在示例中使用filetype。

隨着所提供的類型列表(實際上是一個元組),瀏覽對話框正在優先考慮擴展名爲.tplate的文件。 然後,您可以在下拉列表框中更改此選項以選擇html,python或任何類型的文件。

fname = askopenfilename(filetypes=(("Template files", "*.tplate"), 
            ("HTML files", "*.html;*.htm"), 
            ("Python file", "*.py"), 
            ("All files", "*.*"))) 

如果改變提供的元組的順序,你可以選擇其他類型的第一,

fname = askopenfilename(filetypes=(("Python file", "*.py"), 
            ("HTML files", "*.html;*.htm"), 
            ("All files", "*.*"))) 

檢查這個doc有關選項的更多詳細信息。

相關問題