2017-01-10 6 views
0

このコードを使用して、pdfファイルと印刷ファイル名をターミナルで開こうとします。Tkinterの例外filedialog.askopenfilename

from Tkinter import * 
# Hold onto a global reference for the root window 
root = None 
filename = '' 

def openFile(): 
    global filename 
    root.filename = root.filedialog.askopenfilename(filetypes = (("PDF File" , "*.pdf"),("All Files","*.*"))) 
    print root.filename 

def main(): 
    global root 
    root = Tk() # Create the root (base) window where all widgets go 
    openButton = Button(root, text="Genarate",command=openFile) 
    openButton.pack() 
    root.mainloop() # Start the event loop 


main() 

ですが、コードが正しく動作しません。 Genarateボタンを押すとこのエラーが発生します。

Exception in Tkinter callback 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__ 
    return self.func(*args) 
    File "1gui.py", line 12, in openFile 
    root.filename = root.filedialog.askopenfilename(filetypes = (("PDF File" , "*.pdf"),("All Files","*.*"))) 
    File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1902, in __getattr__ 
    return getattr(self.tk, attr) 
AttributeError: filedialog 

私のコードの間違ったとは何でしょうか?

答えて

3

Tkメインウィンドウなしの属性filedialog.askopenfilenameの場合、tkFileDialogモジュールからaskopenfilenameをインポートする必要があります。

# python2 
from Tkinter import * 
from tkFileDialog import askopenfilename 
# Hold onto a global reference for the root window 
root = None 
filename = '' 

def openFile(): 
    global filename 
    filename = askopenfilename(filetypes = (("PDF File" , "*.pdf"),("All Files","*.*"))) 
    print filename 

def main(): 
    global root 
    root = Tk() # Create the root (base) window where all widgets go 
    openButton = Button(root, text="Genarate",command=openFile) 
    openButton.pack() 
    root.mainloop() # Start the event loop 

main() 

備考:のpython3とインポートは次のようになり

from tkinter import * 
from tkinter.filedialog import askopenfilename 
関連する問題