Some time ago, I learned how to operate excel I want to find a way to operate the file dialog box , I have searched a lot on the Internet with the help of tinker The open , In this way, I feel that the operation is a little slow , And there will be an extra root window , Of course it can be closed , But it's more complicated . There is no way to deal with cases involving multiple file selections .
I'm looking at wxpython modular , There are also file dialog box operations , And it is simple and easy to use , So record it here .
rely on :
pip install wxpython
1、 establish app and frame object
app = wx.App()
frame = wx.Frame(None, title="", pos=(0, 0), size=(100, 100))
This step is just because wx.FileDialog Methods need to be created based on the parent container object , Here I choose to create a frame, there pos、size And other parameters can be set to any value , The main thing is to create such an object . There will be no extra windows .
Be careful :app Objects must be created first and must have variables to accept , Otherwise, there will be the following error .
wx._core.PyNoAppError: The wx.App object must be created first!
2、 Create file dialog box
dlg = wx.FileDialog(parent=frame, message=" Multiple file selection ",
defaultDir=os.getcwd(),
style=wx.FD_MULTIPLE,
wildcard="All files*.*|*.*")
Parameter description :
wx.FD_OVERWRITE_PROMPT example : wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT
3、 Show dialog , Get selected files
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPaths()
print(filename)
dlg.Destroy()
Be careful :dlg.GetPaths The method can only be in wx.FD_MULTIPLE Type , Single file selection requires dlg.GetPath Method .
In fact, there are already many wxpython File operation blog , But most of them are based on integration wx.frame To operate the , When we only need to select the file access path , It is OK to operate like me .
Complete code :
import os
import wx
app = wx.App()
def openFileDialog(style=wx.FD_OPEN, message=" Select File ", defaultDir=os.getcwd(), wildcard="All files(*.*)|*.*"):
frame = wx.Frame(None, title="", pos=(0, 0), size=(100, 100))
dlg = wx.FileDialog(parent=frame, message=message,
defaultDir=defaultDir,
style=style,
wildcard=wildcard)
if dlg.ShowModal() == wx.ID_OK:
if style == wx.FD_MULTIPLE:
return dlg.GetPaths()
return dlg.GetPath()
dlg.Destroy()
return None
print(openFileDialog(wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT))
I have a little encapsulation here , Return to the selected path .
Welcome to leave a message to discuss .
Summary reference blog :https://blog.csdn.net/weixin_30871293/article/details/96099514
More reference :https://www.cnblogs.com/math98/p/14221551.html