1+ # image_viewer_working.py
2+
3+ import wx
4+
5+ class ImagePanel (wx .Panel ):
6+
7+ def __init__ (self , parent , image_size ):
8+ super ().__init__ (parent )
9+ self .max_size = 240
10+
11+ img = wx .Image (* image_size )
12+ self .image_ctrl = wx .StaticBitmap (self ,
13+ bitmap = wx .Bitmap (img ))
14+
15+ browse_btn = wx .Button (self , label = 'Browse' )
16+ browse_btn .Bind (wx .EVT_BUTTON , self .on_browse )
17+
18+ self .photo_txt = wx .TextCtrl (self , size = (200 , - 1 ))
19+
20+ main_sizer = wx .BoxSizer (wx .VERTICAL )
21+ hsizer = wx .BoxSizer (wx .HORIZONTAL )
22+
23+ main_sizer .Add (self .image_ctrl , 0 , wx .ALL , 5 )
24+ hsizer .Add (browse_btn , 0 , wx .ALL , 5 )
25+ hsizer .Add (self .photo_txt , 0 , wx .ALL , 5 )
26+ main_sizer .Add (hsizer , 0 , wx .ALL , 5 )
27+
28+ self .SetSizer (main_sizer )
29+ main_sizer .Fit (parent )
30+ self .Layout ()
31+
32+ def on_browse (self , event ):
33+ """
34+ Browse for an image file
35+ @param event: The event object
36+ """
37+ wildcard = "JPEG files (*.jpg)|*.jpg"
38+ with wx .FileDialog (None , "Choose a file" ,
39+ wildcard = wildcard ,
40+ style = wx .ID_OPEN ) as dialog :
41+ if dialog .ShowModal () == wx .ID_OK :
42+ self .photo_txt .SetValue (dialog .GetPath ())
43+ self .load_image ()
44+
45+ def load_image (self ):
46+ """
47+ Load the image and display it to the user
48+ """
49+ filepath = self .photo_txt .GetValue ()
50+ img = wx .Image (filepath , wx .BITMAP_TYPE_ANY )
51+
52+ # scale the image, preserving the aspect ratio
53+ W = img .GetWidth ()
54+ H = img .GetHeight ()
55+ if W > H :
56+ NewW = self .max_size
57+ NewH = self .max_size * H / W
58+ else :
59+ NewH = self .max_size
60+ NewW = self .max_size * W / H
61+ img = img .Scale (NewW ,NewH )
62+
63+ self .image_ctrl .SetBitmap (wx .Bitmap (img ))
64+ self .Refresh ()
65+
66+
67+ class MainFrame (wx .Frame ):
68+
69+ def __init__ (self ):
70+ super ().__init__ (None , title = 'Image Viewer' )
71+ panel = ImagePanel (self , image_size = (240 ,240 ))
72+ self .Show ()
73+
74+
75+ if __name__ == '__main__' :
76+ app = wx .App (redirect = False )
77+ frame = MainFrame ()
78+ app .MainLoop ()
0 commit comments