Reputation: 448
I try to open pdf file and print file name in terminal using this code.
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()
but, code is not correctly working. when i press Genarate button give this error.
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
what is the wrong of my code?
Upvotes: 0
Views: 1824
Reputation: 16169
Tk
main window as no attribute filedialog.askopenfilename
, you have to import askopenfilename
from the tkFileDialog
module.
# 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()
Remark: with python3 the import would be
from tkinter import *
from tkinter.filedialog import askopenfilename
Upvotes: 3