def __init__(self, parent):
wx.Panel.__init__(self, parent)
imageFile = 'Tile.bmp'
self.bmp = wx.Bitmap(imageFile)
# react to a resize event and redraw image
parent.Bind(wx.EVT_SIZE, self.canvasCallback)
menu = wx.Menu()
menu.Append(wx.ID_ABOUT, "About", "wxPython GUI")
menu.AppendSeparator()
menu.Append(wx.ID_EXIT, "Exit", " Exit the GUI")
menuBar = wx.MenuBar()
menuBar.Append(menu, "File")
parent.SetMenuBar(menuBar)
self.textWidget = wx.TextCtrl(self, size=(280, 80), style=wx.TE_MULTILINE)
button = wx.Button(self, label="Create OpenGL 3D Cube", pos=(60, 100))
self.Bind(wx.EVT_BUTTON, self.buttonCallback, button)
parent.CreateStatusBar()
python类Bitmap()的实例源码
wxPython_Wallpaper.py 文件源码
项目:Python-GUI-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def resize(self, event=None):
"""Handle wx resize events.
Notes:
This method may be called outside the wx event buffer
in order to initialize the panel or reset the drawing
buffer.
"""
size = self.winWidth, self.winHeight = self.GetSize()
if size != self.lastSize: # hack to mitigate multiple consecutive resize events
self.winRadius = min((self.winWidth/2.0, self.winHeight/2.0))
#self.drawingBuffer = wx.Bitmap(self.winWidth, self.winHeight) # wxpython3
self.drawingBuffer = wx.EmptyBitmap(self.winWidth, self.winHeight) # wxpython3
self.lastSize = size
self.refresh()
if event is not None:
event.Skip()
def __init__(self):
'''
@summary: Constructor
@param config_dict: The build configuration, if present
@param load_config: Handle to a config loader method/object
'''
self.language = DEFAULT_LANGUAGE
self.__builder = None
self.config_file_path = None
# Init super - MainFrame
MainFrame.__init__( self, parent=None )
self.console = Console(self.ConsoleTextCtrl)
self.StatusBar.SetStatusText("Ready...")
self.SetIcon(wx.IconFromBitmap(wx.Bitmap("ExeBuilder\\static\\builder_logo.bmp", wx.BITMAP_TYPE_ANY)))
# Update GUI Visuals
self.update_gui_visuals()
# Set initial event handlers
self.set_events()
def update_gui_visuals(self):
'''
@summary: Updates the GUI with any aesthetic changes following initialising. This
inludes updating labels and other widgets
'''
# Version
self.TitleLabel.SetLabel(TITLE)
self.SetTitle(TITLE)
# Set Logo Image
self.LogoBitmap.SetBitmap(
wx.Bitmap(
"ExeBuilder\\static\\builder_logo.bmp"
)
)
# Set debug to default level
self.DebugLevelChoice.SetSelection(
self.DebugLevelChoice.FindString(
BUILDER_CONFIG_ITEMS["debug_level"]["default"]
)
)
def _drawPointLabel(self, mDataDict):
"""Draws and erases pointLabels"""
width = self._Buffer.GetWidth()
height = self._Buffer.GetHeight()
if sys.platform != "darwin":
tmp_Buffer = wx.Bitmap(width, height)
dcs = wx.MemoryDC()
dcs.SelectObject(tmp_Buffer)
dcs.Clear()
else:
tmp_Buffer = self._Buffer.GetSubBitmap((0, 0, width, height))
dcs = wx.MemoryDC(self._Buffer)
self._pointLabelFunc(dcs, mDataDict) # custom user pointLabel function
dc = wx.ClientDC(self.canvas)
dc = wx.BufferedDC(dc, self._Buffer)
# this will erase if called twice
dc.Blit(0, 0, width, height, dcs, 0, 0, self._logicalFunction)
if sys.platform == "darwin":
self._Buffer = tmp_Buffer
def DrawFromSelectedNode(self, msg):
t = msg.replace("][", ",").replace("[", "").replace("]", "").split(",")
osx = int(t[0])
osy = int(t[1])
oex = int(t[2])
oey = int(t[3])
i = wx.Bitmap(os.path.join(self.screenShotDir, "screenshot.png"))
dc = wx.MemoryDC(i)
dc.SetPen(wx.Pen(wx.RED, 1))
#???(wxpython????drawline?drawlines, ??drawrect??????)
dc.DrawLine(osx, osy, osx, oey)
dc.DrawLine(osx, osy, oex, osy)
dc.DrawLine(oex, osy, oex, oey)
dc.DrawLine(osx, oey, oex, oey)
dc.SelectObject(wx.NullBitmap)
self.screenShot.SetBitmap(i)
self.Refresh(eraseBackground=True, rect=None)
def updateStatus(self, msg):
# siz = self.GetSize()
if os.path.isfile(msg):
if ".png" in msg:
self.clearScreenShot(self.defaultScreenShotImage)
newScreenShotPath = os.path.join(self.screenShotDir, "screenshot.png")
self.newScreenShot = wx.Bitmap(newScreenShotPath)
print("????????",self.newScreenShot.GetSize())
self.screenShot.SetBitmap(self.newScreenShot)
self.Refresh(eraseBackground=True, rect=None)
self.notUseDetaul = 1
else:
pass
else:
if msg == "?????????PC??":
self.statusBar.ForegroundColour = "red"
self.statusBar.SetLabel(msg)
else:
self.statusBar.ForegroundColour = "blue"
if "ERROR: could not get idle state." in msg:
self.statusBar.SetLabel(msg)
self.statusBar.SetLabel(msg)
def __init__(self, parent=None, fdir='./', title='pyDataViewer',
size=(800,600), **kwargs):
wx.Frame.__init__(self,parent,title=title,size=size)
try:
_icon = wx.EmptyIcon()
_icon.CopyFromBitmap(
# postproclib.visualiser.__path__ (pplvpath) is a list
wx.Bitmap(pplvpath[0]+"/logo.gif", wx.BITMAP_TYPE_ANY)
)
self.SetIcon(_icon)
except IOError:
print('Couldn\'t load icon')
self.dirchooser = DirectoryChooserPanel(self, fdir)
self.vbox = wx.BoxSizer(wx.VERTICAL)
self.vbox.Add(self.dirchooser, 0, wx.EXPAND, 0)
self.SetSizer(self.vbox)
self.visualiserpanel = None
self.new_visualiserpanel(fdir)
self.fdir = fdir
self.set_bindings()
def HitTest(self, x, y):
"""
Test if point is inside button
@param x: X coordinate of point
@param y: Y coordinate of point
@return: True if button is active and displayed and point is inside
button
"""
# Return immediately if button is hidden or inactive
if not (self.IsShown() and self.IsEnabled()):
return False
# Test if point is inside button
w, h = self.Bitmap.GetSize()
rect = wx.Rect(self.Position.x, self.Position.y, w, h)
return rect.InsideXY(x, y)
def buildToolsBar(parent, datas):
box = wx.BoxSizer( wx.HORIZONTAL )
#toolsbar = wx.ToolBar( parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TB_HORIZONTAL )
toolsbar = wx.Panel( parent, wx.ID_ANY,
wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
toolsbar.SetSizer( box )
add_tools(toolsbar, datas[1][0][1], None)
gifpath = os.path.join(root_dir, "tools/drop.gif")
btn = wx.BitmapButton(toolsbar, wx.ID_ANY, make_bitmap(wx.Bitmap(gifpath)),
wx.DefaultPosition, (32, 32), wx.BU_AUTODRAW|wx.RAISED_BORDER)
box.Add(btn)
btn.Bind(wx.EVT_LEFT_DOWN, lambda x:menu_drop(parent, toolsbar, datas, btn, x))
add_tools(toolsbar, datas[1][1][1])
return toolsbar
def draw_image(self, dc, ndarr, back, mode, rect, scale, dirty):
win = cross(self.box, rect)
win2 = trans(rect, win)
sx = sy = 1.0/scale
box = multiply(win2, sx, sy)
M = np.array([sx, sy])
O = (win2[1]*sx, win2[0]*sy)
shape = (win2[3], win2[2])
if dirty:
start = time()
rst = self.merge(ndarr, back, M, O, mode, shape, win2, self.ips.lookup)
self.bmp = wx.Bitmap.FromBuffer(win2[2], win2[3], memoryview(rst))
print(time()-start)
dc.DrawBitmap(self.bmp, win[0], win[1])
def __set_properties(self):
# begin wxGlade: Login.__set_properties
self.SetTitle("Login")
#_icon = wx.EmptyIcon()
#_icon.CopyFromBitmap(wx.Bitmap("/media/f67bc164-f440-4c0f-9e9b-3ad70ff1adc2/home/asif/Desktop/waiter animation/2.gif", wx.BITMAP_TYPE_ANY))
#self.SetIcon(_icon)
self.SetSize((462, 239))
self.SetFocus()
self.label_1.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.combo_box_1.SetSelection(0)
self.label_2.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.BOLD, 0, ""))
self.text_ctrl_1.SetMinSize((185, 30))
self.button_1.SetMinSize((85, 35))
self.button_1.SetFont(wx.Font(11, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Ubuntu"))
self.button_2.SetMinSize((85, 35))
self.button_2.Disable()
# end wxGlade
def onView(self):
"""
Attempts to load the image and display it
"""
filepath = self.photoTxt.GetValue()
img = wx.Image(filepath, wx.BITMAP_TYPE_ANY)
# scale the image, preserving the aspect ratio
W = img.GetWidth()
H = img.GetHeight()
if W > H:
NewW = self.PhotoMaxSize
NewH = self.PhotoMaxSize * H / W
else:
NewH = self.PhotoMaxSize
NewW = self.PhotoMaxSize * W / H
img = img.Scale(NewW,NewH)
self.imageCtrl.SetBitmap(wx.Bitmap(img))
self.panel.Refresh()
self.mainSizer.Fit(self.frame)
wxPython_Wallpaper_simple.py 文件源码
项目:Python-GUI-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
def __init__(self, parent):
wx.Panel.__init__(self, parent)
imageFile = 'Tile.bmp'
self.bmp = wx.Bitmap(imageFile)
# react to a resize event and redraw image
parent.Bind(wx.EVT_SIZE, self.canvasCallback)
button = wx.Button(self, label="Quit")
self.Bind(wx.EVT_BUTTON, self.buttonCallback, button)
parent.CreateStatusBar()
def load_zad(self, file_path, fit=True):
img = wx.Image(file_path, wx.BITMAP_TYPE_ANY)
if fit:
w, h = img.GetWidth(), img.GetHeight()
max_w, max_h = self.images_panel.GetSize()
target_ratio = min(max_w / float(w), max_h / float(h))
new_w, new_h = [int(x * target_ratio) for x in (w, h)]
img = img.Scale(new_w, new_h, wx.IMAGE_QUALITY_HIGH)
self.images_panel.drawable_bitmap = wx.Bitmap(img)
self.images_panel.Refresh()
def no_show(self):
self.images_panel.drawable_bitmap = \
wx.Bitmap(wx.Image(*self.images_panel.drawable_bitmap.GetSize()))
self.images_panel.Refresh()
def AssignImages(self, active, inactive):
self.active_tab_bitmap = wx.Bitmap(active)
self.inactive_tab_bitmap = wx.Bitmap(inactive)
self._nImgSize = max(self.active_tab_bitmap.GetHeight(), self.inactive_tab_bitmap.GetHeight() )
def AssignForeground(self, fg):
self.foreground = wx.Bitmap(fg)
def AssignIllst(self, image, pos):
self.illst.append( (wx.Bitmap(image), pos) )
def CreateBitmap(self, artid, client, size):
if not artid.startswith('priv'):
return wx.NullBitmap
artid = artid.split('/')[1:] # Split path and remove 'priv'
artid = '/'.join(artid) # rejoin remaining parts
fpath = appconstants.getdatapath(artid)
return wx.Bitmap(fpath, wx.BITMAP_TYPE_ANY)
def __init__(self, parent, title):
style = wx.DEFAULT_FRAME_STYLE & ~(
wx.RESIZE_BORDER | wx.MAXIMIZE_BOX |
wx.MINIMIZE_BOX|wx.CLOSE_BOX)
wx.Frame.__init__(self, parent, title=title,
style=style, size=(400,60))
self.textbox = wx.TextCtrl(self)
img = wx.Image("matags.png", wx.BITMAP_TYPE_ANY)
bmp = wx.Bitmap(img)
self.icon = wx.Icon()
self.icon.CopyFromBitmap(bmp)
self.SetIcon(self.icon)
self.tbIcon = wx.adv.TaskBarIcon()
self.tbIcon.SetIcon(self.icon)
self.Show(True)
self.Centre()
self.reg_hot_keys()
self.Bind(wx.EVT_HOTKEY, self.on_extract_tag,
id=self.hotkeys['extract_tag'][0])
self.Bind(wx.EVT_HOTKEY, self.on_close,
id=self.hotkeys['quit'][0])
self.Bind(wx.EVT_HOTKEY, self.on_activate,
id=self.hotkeys['activate'][0])
self.Bind(wx.EVT_HOTKEY, self.on_refresh,
id=self.hotkeys['refresh'][0])
self.textbox.Bind(wx.EVT_CHAR, self.check_key)
# do not use EVT_KEY_DOWN,
# it becomes difficult to get lower case
# self.textbox.Bind(wx.EVT_KEY_DOWN, self.check_key)
# self.Bind(wx.EVT_CLOSE, self.on_close)
self.Bind(wx.EVT_ICONIZE, self.on_iconify)
self.matags = MaTags()
# try:
# except Exception as e:
# self.textbox.ChangeValue(e.args[0].decode('utf8', 'ignore'))
# self.textbox.Disable()
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
wx.Frame.__init__(self, *args, **kwds)
self.label_5 = wx.StaticText(self, wx.ID_ANY, "Cadena Busqueda:")
self.text_ctrl_bucar = wx.TextCtrl(self, wx.ID_ANY, "")
self.button_buscar = wx.Button(self, wx.ID_ANY, "Buscar")
self.label_6 = wx.StaticText(self, wx.ID_ANY, "total VM: 333")
self.bitmap_button_1 = wx.BitmapButton(self, wx.ID_ANY, wx.Bitmap("/home/mario/pyvmwareclient/wxglade/recicla.png", wx.BITMAP_TYPE_ANY))
self.list_ctrl_1 = wx.ListCtrl(self, wx.ID_ANY)
self.__set_properties()
self.__do_layout()
# end wxGlade
def OnSize(self, event):
# The buffer is initialized in here, so that the buffer is always
# the same size as the Window.
if event is None:
return 0,0
width, height = self.GetClientSize()
if width <= 0 or height <=0:
return 0,0
# Make new off-screen bitmap: this bitmap will always have the
# current drawing in it, so it can be used to save the image to
# a file, or whatever.
if width and height:
# Macs can generate events with 0-size values
self._buffer = wx.Bitmap(width, height)
self.UpdateDrawing()
def UpdateImage(self, axis, position):
object = self.object
idx = position - 1
if axis == 1:
imagedata = object[idx,:,:]
elif axis == 2:
imagedata = object[:,idx,:]
else:
imagedata = object[:,:,idx]
imagedata[imagedata < 1e-6] = 1.0
imagedata = numpy.log(imagedata)
imagedata = imagedata - imagedata.min()
if imagedata.max() > 0:
imagedata = (255.0/imagedata.max())*imagedata
else:
imagedata = 255.0*imagedata
imagedatalow = numpy.uint8(imagedata)
self.impil = Image.fromarray(imagedatalow, 'L').resize((self.sx,self.sy))
if IsNotWX4():
self.imwx = wx.EmptyImage( self.impil.size[0], self.impil.size[1] )
else:
self.imwx = wx.Image( self.impil.size[0], self.impil.size[1] )
self.imwx.SetData( self.impil.convert( 'RGB' ).tobytes() )
if IsNotWX4():
bitmap = wx.BitmapFromImage(self.imwx)
else:
bitmap = wx.Bitmap(self.imwx)
if IsNotWX4():
self.bmp = wx.BitmapFromImage(self.imwx)
else:
self.bmp = wx.Bitmap(self.imwx)
self.image.SetBitmap(bitmap)
self.Refresh()
self.Layout()
def UpdateImage(self, axis, position):
object = self.object
idx = position - 1
if axis == 1:
imagedata = numpy.array(object[idx,:,:])
elif axis == 2:
imagedata = numpy.array(object[:,idx,:])
else:
imagedata = numpy.array(object[:,:,idx])
imagedata[imagedata < 1e-6] = 1.0
imagedata = numpy.log(imagedata)
imagedata = imagedata - imagedata.min()
if imagedata.max() > 0:
imagedata = (255.0/imagedata.max())*imagedata
else:
imagedata = 255.0*imagedata
imagedatalow = numpy.uint8(imagedata)
self.impil = Image.fromarray(imagedatalow, 'L').resize((self.sx,self.sy))
if IsNotWX4():
self.imwx = wx.EmptyImage( self.impil.size[0], self.impil.size[1] )
else:
self.imwx = wx.Image( self.impil.size[0], self.impil.size[1] )
self.imwx.SetData( self.impil.convert( 'RGB' ).tobytes() )
if IsNotWX4():
bitmap = wx.BitmapFromImage(self.imwx)
else:
bitmap = wx.Bitmap(self.imwx)
self.bmp = bitmap
self.image.SetBitmap(bitmap)
self.Refresh()
self.Layout()
def OnSize(self, event):
# The Buffer init is done here, to make sure the buffer is always
# the same size as the Window
Size = self.canvas.GetClientSize()
if Size.width <= 0 or Size.height <= 0:
return
Size.width = max(1, Size.width)
Size.height = max(1, Size.height)
# Make new offscreen bitmap: this bitmap will always have the
# current drawing in it, so it can be used to save the image to
# a file, or whatever.
#self._Buffer = wx.Bitmap(Size.width, Size.height)
if IsNotWX4():
self._img = wx.EmptyImage(Size.width,Size.height)
self._Buffer = wx.BitmapFromImage(self._img)
else:
self._img = wx.Image(Size.width,Size.height)
self._Buffer = wx.Bitmap(self._img)
self._Buffer.SetHeight(Size.height)
self._Buffer.SetWidth(Size.width)
self._setSize()
self.last_PointLabel = None # reset pointLabel
if self.last_draw is None:
self.Clear()
else:
graphics, xSpec, ySpec = self.last_draw
self._Draw(graphics, xSpec, ySpec)
def display_matches(self):
self.mainSizer = wx.BoxSizer(wx.VERTICAL)
self.sizer = wx.BoxSizer(wx.HORIZONTAL)
self.images = []
self.labels = []
m = self.session.matches()
for i in range(len(m)):
match = m[i]
# Thumb
fd = urlopen(match.user.thumbnails[0])
file = io.BytesIO(fd.read())
img = wx.Image(file, wx.BITMAP_TYPE_ANY)
self.images.append(wx.StaticBitmap(self.panel, wx.ID_ANY,
wx.Bitmap(img)))
self.images[i].Bind(wx.EVT_BUTTON, self.onClick)
# Label for name
self.labels.append(wx.StaticText(self.panel, label=match.user.name))
# Add to sizer
self.mainSizer.Add(self.labels[i], 0, wx.ALL, 5)
self.mainSizer.Add(self.images[i], 0, wx.ALL, 5)
self.mainSizer.Add(self.sizer, 0, wx.ALL, 5)
self.panel.SetSizer(self.mainSizer)
self.panel.Layout()
self.panel.Refresh()
def draw_box(self):
x1, x2 = self.plot._point2ClientCoord(*self.selected)[::2]
dc = wx.ClientDC(self.plot.canvas)
dc.SetLogicalFunction(wx.INVERT)
dc.DrawRectangle(x1, 0, x2, dc.GetSize()[1])
dc.SetLogicalFunction(wx.COPY)
# def clear(self):
# # An experimental way to clear the canvas without redrawing the plot every time
# # dc.Blit() usage from SOF.
# if self.selection_drawn:
# self.draw_box() # clear old
# self.selection_drawn = False
# dc = wx.ClientDC(self.plot.canvas)
# size = dc.GetSize()
# bmp = wx.Bitmap(size.width, size.height)
# prev_dc = wx.MemoryDC()
# prev_dc.SelectObject(bmp)
# prev_dc.Blit(
# 0, # Copy to this X coordinate
# 0, # Copy to this Y coordinate
# size.width, # Copy this width
# size.height, # Copy this height
# dc, # From where do we copy?
# 0, # What's the X offset in the original DC?
# 0 # What's the Y offset in the original DC?
# )
# prev_dc.SelectObject(wx.NullBitmap)
# dc.Clear()
# dc.DrawBitmap(bmp, 0, 0)
# # if self.plot.last_draw is not None:
# # self.plot.Draw(self.plot.last_draw[0])
def OnEraseBackground(self, evt):
"""
Add a picture to the background
"""
# yanked from ColourDB.py
dc = evt.GetDC()
if not dc:
dc = wx.ClientDC(self)
rect = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rect)
dc.Clear()
# bmp = wx.Bitmap("/home/pi/Desktop/GoBox/Troubleshooting_GUI/dex.png") # Draw the photograph.
# dc.DrawBitmap(bmp, 0, 400) # Absolute position of where to put the picture
def SetPageBitmap(self, idx, bitmap):
"""Function that fix difference in setting picture on tab between
wx.Notebook and wx.aui.AUINotebook.
:param idx: Tab index.
:param bitmap: wx.Bitmap to define on tab.
:returns: True if operation succeeded
"""
return self.TabsOpened.SetPageBitmap(idx, bitmap)
# -------------------------------------------------------------------------------
# Dialog Message Functions
# -------------------------------------------------------------------------------