Come creare l'effetto hover su StaticBitmap in wxpython?
Domanda
Voglio creare l'effetto hover su StaticBitmap - Se il cursore del mouse si trova sulla bitmap, mostra un'immagine, in caso contrario, mostra la seconda immagine. È un programma banale (funziona perfettamente con un pulsante). Tuttavia, StaticBitmap non emette eventi EVT_WINDOW_ENTER, EVT_WINDOW_LEAVE.
Posso lavorare con EVT_MOTION. Se le immagini vengono commutate quando il cursore si trova sul bordo dell'immagine, a volte l'interruttore non funziona. (Principalmente con movimento rapido oltre il bordo).
Codice di esempio:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
def onWindow(event):
print "window event:", event.m_x, event.m_y
def onMotion(event):
print "motion event:", event.m_x, event.m_y
app = wx.App()
imageA = wx.Image("b.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
imageB = wx.Image("a.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
frame = wx.Frame(None, wx.ID_ANY, title="Hover effect", size=(100+imageA.GetWidth(), 100+imageA.GetHeight()))
w = wx.Window(frame)
bmp = wx.StaticBitmap(w, -1, imageA, (50, 50), (imageA.GetWidth(), imageA.GetHeight()))
bmp.Bind(wx.EVT_MOTION, onMotion)
bmp.Bind(wx.EVT_ENTER_WINDOW, onWindow)
bmp.Bind(wx.EVT_LEAVE_WINDOW, onWindow)
frame.Show()
app.MainLoop()
Soluzione
Sembra che questo sia un bug di wxGTK, gli eventi ENTER e LEAVE funzionano bene su Windows. Dovresti indirizzare l'attenzione degli sviluppatori principali sul problema, un buon posto per farlo è il loro bug tracker . Questo è un problema che non dovresti aggirare intorno a IMHO.
Ho scoperto che GenericButtons non ha questo problema su wxGTK, quindi forse puoi usarlo fino a quando StaticBitmap non viene riparato.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
from wx.lib import buttons
def onWindow(event):
print "window event:", event.m_x, event.m_y
def onMotion(event):
print "motion event:", event.m_x, event.m_y
app = wx.App()
imageA = wx.Image("b.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
imageB = wx.Image("a.gif", wx.BITMAP_TYPE_ANY).ConvertToBitmap()
frame = wx.Frame(None, wx.ID_ANY, title="Hover effect", size=(100+imageA.GetWidth(), 100+imageA.GetHeight()))
w = wx.Window(frame)
#bmp = wx.StaticBitmap(w, -1, imageA, (50, 50), (imageA.GetWidth(), imageA.GetHeight()))
bmp = buttons.GenBitmapButton(w, -1, imageA, style=wx.BORDER_NONE)
#bmp.Bind(wx.EVT_MOTION, onMotion)
bmp.Bind(wx.EVT_ENTER_WINDOW, onWindow)
bmp.Bind(wx.EVT_LEAVE_WINDOW, onWindow)
frame.Show()
app.MainLoop()
Altri suggerimenti
Potrebbe esserci un bug nell'implementazione di wxStaticBitmap, ma se wxBitmapButton funziona puoi usarlo per lo stesso effetto, con meno codice
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx
app = wx.App()
frame = wx.Frame(None, wx.ID_ANY, title="Hover effect")
w = wx.Window(frame)
c = wx.BitmapButton(w, -1, wx.EmptyBitmap(25,25), style = wx.NO_BORDER)
c.SetBitmapHover(wx.EmptyBitmap(3,3))
frame.Show()
app.MainLoop()