在 wxpython 中发布.listen 大小更改事件的正确方法是什么?
我确信这很简单,但我不知道如何在类之间很好地实现它(请原谅任何新手明显的错误)。
我可以使用 pypubsub 发送事件,但这仅在创建 UI 类时被侦听器捕获(即侦听一次,而不是在随后调整框架大小时)。
听众:
# listeners - define before the event
pub.subscribe(self.on_resized, 'size_changed')
pub.subscribe(self.on_relocated, 'pos_changed')
出版商:
def on_size(self, event):
_size = event.GetSize()
pub.sendMessage('size_changed', size=_size)
def on_move(self, event):
_pos = event.GetPosition()
pub.sendMessage('pos_changed', pos=_pos)
我试过使用 CallAfter - 但这似乎没有帮助(不太确定我在用这个做什么,但认为它可能会在之后调用事件)
def on_size(self, event):
_size = event.GetSize()
wx.CallAfter(pub.sendMessage, 'size_changed', size=_size)
def on_move(self, event):
_pos = event.GetPosition()
wx.CallAfter(pub.sendMessage, 'pos_changed', pos=_pos)
我还尝试了 CallAfter 的第二种变体,它似乎被听了两次(一种改进?),但我理解这是由结果 AssertionError 错误地格式化
def on_size(self, event):
_size = event.GetSize()
# test incorrect formatting of call after...
wx.CallAfter(pub.sendMessage('size_changed', size=_size))
def on_move(self, event):
_pos = event.GetPosition()
pub.sendMessage('pos_changed', pos=_pos)
在此先感谢您的任何帮助/指点
最小演示:
import pubsub.pub as pub
import wx
class UI(wx.Frame):
def __init__(self, *args, **kwargs):
# init base class
super().__init__(*args, **kwargs)
# bindings
self.Bind(wx.EVT_MOVE, self.on_move)
self.Bind(wx.EVT_SIZE, self.on_size)
def on_size(self, event):
_size = event.GetSize()
print('[UI] resized to :', _size)
# broadcast new size
pub.sendMessage('size_changed', size=_size)
# wx.CallAfter(pub.sendMessage, 'size_changed', size=_size)
# test incorrect formatting of call after...
# wx.CallAfter(pub.sendMessage('size_changed', size=_size))
def on_move(self, event):
_pos = event.GetPosition()
print('[UI] moved to :', _pos)
# broadcast new location
pub.sendMessage('pos_changed', pos=_pos)
# wx.CallAfter(pub.sendMessage, 'pos_changed', pos=_pos)
class CustomFrame(object):
def __init__(self, parent=None, _id=wx.ID_ANY, title='test'):
# listeners - define before the event
pub.subscribe(self.on_resized, 'size_changed')
pub.subscribe(self.on_relocated, 'pos_changed')
self._id = _id
self._ui = UI(parent=parent, id=_id, title=title)
self._ui.Show()
def on_resized(self, size):
print('[CustomFrame] The new size is :=', size)
# do something with the new size
def on_relocated(self, pos):
print('[CustomFrame] The new location is :=', pos)
# do something with the new position
if __name__ == '__main__':
app = wx.App()
CustomFrame(title='Demo')
app.MainLoop()