我尝试使用此代码打开pdf文件并在终端中打印文件名。
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
我的代码有什么问题?
答案 0 :(得分:3)
Tk
主窗口为无属性filedialog.askopenfilename
,您必须从askopenfilename
模块导入tkFileDialog
。
# 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