A simple image browser instance implemented using wxpython,
I crawled more than n images last time, but there was a problem during browsing.
Image browsers generally display images by name, and the names of images are incremented by numbers. For example, 3 will always be behind 10, so you cannot view images quickly.
Therefore, in order to make it easier for you to view images, and to learn, you decided to create your own image browser.
Objective: To view the directory, display images in the same folder through the scroll wheel, and customize the sorting.
Step 0:To implement a graphical interface, I use wxPython.
As for how to install and simply use wxpython, you can retrieve a lot of information from the Internet.
By default, you know how to generate your own frame.
Step 1:Browse Directory.
This function is similar to opening "my computer", and then constantly entering the folder and returning.
After several attempts, I decided to use listbox.
I Initialize an app. Using a frame to implement the directory function, there is only one listbox on it; using another frame to implement the image display function, the two frames transmit information through the app.
Copy codeThe Code is as follows:
For _ dir in OS. listdir (dir ):
# Do something
Such as OS. path. split (), OS. path. splitext (), and OS. path. isdir () are common methods.
The display directory is a process of continuously obtaining the directory you selected, entering the directory, reading the directory under it, clearing listbox, displaying the directory, and changing the working path.
When the directory is displayed, the custom sorting function is displayed. After processing the image name, convert it to numbers, sort it, and re-assemble it to increase by number.
Copy codeThe Code is as follows:
Self. list. Bind (wx. EVT_LISTBOX_DCLICK, self. OnDClick)
At the same time, the double-click event is bound to listbox through the above method. If you double-click a directory, the directory is displayed. Otherwise, the image is displayed through the app.
At the same time, this frame requires two methods, that is, to obtain the previous or next image for subsequent app calls.
Step 2:Show Image
This image was very troublesome at first, but it was easy to understand.
I use a frame to display images.
The frame is blank and there is a wx. StaticBitmap. When the image is displayed, you only need to write bitmap to the staticbitmap. At the beginning, I constantly created staticbitmap, which led to some reasons why I could see it but didn't know why.
Then, the scroll wheel event is detected on the frame. The GetNextImage and GetPreImage methods of the app are called up or down and the obtained images are displayed.
There is also the size of the image. I first set a maximum value and a minimum value to limit the image to a certain range.
Copy codeThe Code is as follows:
Bmp = image. Scale (size [0], size [1]). ConvertToBitmap ()
Self.bmp. SetSize (size) # bmp is staticbitmap
Self.bmp. SetBitmap (bmp)
However, it is uncomfortable to see images in a small window, so the image window is made full screen.
Copy codeThe Code is as follows:
Self. ShowFullScreen (True, style = wx. FULLSCREEN_ALL)
How to exit the full screen mode is required. I send a message by pressing the key. The command window is closed or displayed. If it is displayed, It is disabled (actually hidden). If it is hidden, it is displayed. Note that this event must be bound to the app.
Copy codeThe Code is as follows:
Self. Bind (wx. EVT_KEY_DOWN, self. OnKeyDown)
Then the image needs to be zoomed in and out. So I trigger it by pressing the button again. To zoom in or out, you only need to change the maximum value of staticbitmap and adapt bmp to that size.
Because the screen is full, you need to be able to move the image. Only staticbitmap needs to be moved.
Copy codeThe Code is as follows:
# Note: bind the event to staticbitmap.
Self.bmp. Bind (wx. EVT_LEFT_DOWN, self. OnLeftDown)
Self.bmp. Bind (wx. EVT_LEFT_UP, self. OnLeftUp)
Self.bmp. Bind (wx. EVT_MOTION, self. OnMotion)
At this point, the main points are all finished. below is all the code. After careful reading, we will find some new usage,
However, this picture browser is probably only enough for me to use, but it is quite easy to use. full screen pictures can be displayed and pictures can be moved freely. The shortcut key is very convenient to exit the full screen.
There are still some imperfections that need to be improved. I hope to have more exchanges with you ~
I would like to thank the authors who have been referenced by me a lot during this period.
Copy codeThe Code is as follows:
#! /Usr/bin/env Python
# Coding = UTF-8
# Filename: PictureBrowser. py
# Date: 2012-10-11
Import wx
Import OS
Import sys
Import string
# Do you have H disks? If no, modify the initial loading path in this initialization function.
Class PBDirFrame (wx. Frame ):
Def _ init _ (self, app ):
Wx. Frame. _ init _ (self, None,-1, "select folder", size = (250,500 ))
Self. app = app
# Set Font
Font = wx. Font (12, wx. DEFAULT, wx. NORMAL, wx. NORMAL, False, 'courier new ')
Self. SetFont (font)
# Folder listbox
Self. list = wx. ListBox (self,-1, (200,600), (), '', wx. LB_SINGLE)
Self. list. Bind (wx. EVT_LISTBOX_DCLICK, self. OnDClick)
# Load the current folder
# Curdir = OS. getcwd () # modify the initial path here. This is the current working path.
Curdir = 'H :\\'
OS. chdir (curdir)
Self. LoadDir (curdir)
# Binding events
Self. Bind (wx. EVT_CLOSE, self. OnClose)
# Display window
Self. Show ()
Def OnClose (self, event ):
Self. Destroy ()
Self. app. Close ()
# Listbox double-click event
Def OnDClick (self, event ):
If self. list. GetSelection () = 0: # Check whether the previous folder is selected.
Path = OS. getcwd ()
Pathinfo = OS. path. split (path)
Dir = pathinfo [0]
Else: # Get the next folder
Dir = self. list. GetStringSelection ()
If OS. path. isdir (dir): # enter the folder
Self. LoadDir (dir)
Elif OS .path.splitext(dir00000000-1000000000000'.jpg ': # Show Image
Self. app. ShowImage (dir)
# Load folders. If you want to define your own sorting, modify this method ~
Def LoadDir (self, dir ):
# Do not operate on directories
If not OS. path. isdir (dir ):
Return
Self. list. Clear () # Clear
Self. list. Append ('...') # Add a folder flag to return to the previous layer.
Dirs = []
Jpgs = []
Nnjpgs = []
For _ dir in OS. listdir (dir ):
If OS. path. isdir (dir + OS. path. sep + _ dir ):
Dirs. append (_ dir)
Else:
Info = OS. path. splitext (_ dir)
If infographic-1 has been created '.jpg ':
If info [0]. isdigit ():
Jpgs. append (string. atoi (info [0]) # convert to a number
Else:
Nnjpgs. append (_ dir)
Jpgs. sort ()
For _ jpgs in jpgs:
Self.list.append(str(_jpgs?}'.jpg ')
For _ nnjpgs in nnjpgs:
Self. list. Append (_ nnjpgs)
For _ dirs in dirs:
Self. list. Append (_ dirs)
OS. chdir (dir) # Set the working path
# Obtain the next image to be displayed
Def GetNextImage (self ):
Index = self. list. GetSelection ()
I = index
While I + 1 <self. list. GetCount ():
I + = 1
If OS .path.splitext(self.list.getstring( I ?#-1}}}'.jpg ':
Break
If I <self. list. GetCount ():
Index = I
Self. list. SetSelection (index)
Return self. list. GetStringSelection ()
# Obtain the previous image
Def GetPreImage (self ):
Index = self. list. GetSelection ()
I = index
While I-1> 0:
I-= 1
If OS .path.splitext(self.list.getstring( I ?#-1}}}'.jpg ':
Break
If I> 0:
Index = I
Self. list. SetSelection (index)
Return self. list. GetStringSelection ()
Class PBPicFrame (wx. Frame ):
Max_width = 400
Max_height = 600
Def _ init _ (self, app ):
Wx. Frame. _ init _ (self, None,-1, "show image", size = (400,400) #, style = wx. SIMPLE_BORDER)
# Whether to move the image logo
Self. bmoved = False
Self. app = app
# Staticbitmap
Self.bmp = wx. StaticBitmap (self, 0, wx. NullBitmap, (400,400 ))
Self. Bind (wx. EVT_MOUSEWHEEL, self. OnChangeImage)
Self.bmp. Bind (wx. EVT_LEFT_DOWN, self. OnLeftDown)
Self.bmp. Bind (wx. EVT_LEFT_UP, self. OnLeftUp)
Self.bmp. Bind (wx. EVT_MOTION, self. OnMotion)
Self. Bind (wx. EVT_KEY_DOWN, self. OnKeyDown)
Self. ShowFullScreen (True, style = wx. FULLSCREEN_ALL)
Self. Hide ()
Def ShowImage (self, path ):
If OS. path. splitext (path) [-1]! '.Jpg ':
Return
Self.bmp path = path
Image = wx. Image (path, wx. BITMAP_TYPE_JPEG)
Bmp = image. ConvertToBitmap ()
Size = self. GetSize (bmp)
Bmp = image. Scale (size [0], size [1]). ConvertToBitmap ()
Self.bmp. SetSize (size)
Self.bmp. SetBitmap (bmp)
Self. Show ()
Def GetSize (self, bmp ):
Width = bmp. GetWidth ()
Height = bmp. GetHeight ()
If width> self. max_width:
Height = height * self. max_width/width
Width = self. max_width
If height> self. max_height:
Width = width * self. max_height/height
Height = self. max_height
Size = width, height
Return size
Def OnChangeImage (self, event ):
Rotation = event. GetWheelRotation ()
If rotation <0:
Self. app. ShowNextImage ()
Else:
Self. app. ShowPreImage ()
Def OnLeftDown (self, event ):
Self. pos = event. GetX (), event. GetY ()
Self. bmoved = True
Def OnLeftUp (self, event ):
Self. bmoved = False
Def OnMotion (self, event ):
If not self. bmoved:
Return
Pos = event. GetX (), event. GetY ()
Dx = pos [0]-self. pos [0]
Dy = pos [1]-self. pos [1]
Pos = self.bmp. GetPosition ()
Pos = pos [0] + dx, pos [1] + dy
Self.bmp. SetPosition (pos)
Def OnKeyDown (self, event ):
Keycode = event. GetKeyCode ()
If keycode = 49: # Number 1 zoom in
Self. SizeUp ()
Elif keycode = 50: # reduce the number by 2
Self. SizeDown ()
Event. Skip () # This seems very important. At the same time, it is necessary to trigger the shortcut keys on the app.
Def SizeUp (self ):
Self. max_width + = 50
Self. max_height + = 75
Self.ShowImage(self.bmp path)
Def SizeDown (self ):
Self. max_width-= 50
Self. max_height-= 75
Self.ShowImage(self.bmp path)
Class PBApp (wx. App ):
# Redirect = False output information to the dos Interface
Def _ init _ (self, redirect = False ):
Wx. App. _ init _ (self, redirect)
Def OnInit (self ):
# Display the folder list Interface
Self. dirframe = PBDirFrame (self)
# Display image Interface
Self. picframe = PBPicFrame (self)
# Binding events
Self. Bind (wx. EVT_KEY_DOWN, self. OnKeyDown)
Return True
Def ShowImage (self, path ):
# Print 'showing app img ', path
Self. picframe. ShowImage (path)
Self. picframe. SetFocus ()
Def ShowNextImage (self ):
Path = self. dirframe. GetNextImage ()
Self. ShowImage (path)
Def ShowPreImage (self ):
Path = self. dirframe. GetPreImage ()
Self. ShowImage (path)
Def OnKeyDown (self, event ):
Keycode = event. GetKeyCode ()
# Print keycode
If keycode = 27: # ESC key
# Switching between display and hide of image forms
If self. picframe. IsShown ():
Self. picframe. Hide ()
Else:
Self. picframe. Show ()
Def Close (self ):
Self. picframe. Close ()
Def main ():
App = PBApp ()
App. MainLoop ()
If _ name __= = '_ main __':
Main ()