在我的 wxPython 应用程序中,我创建了一个 wx.ScrolledPanel
,其中有一个需要滚动的大 wx.StaticBitmap
。
确实出现了滚动条,我可以用它们滚动,但我也希望能够用鼠标滚轮和键盘上的箭头键滚动。如果“Home”、“Page Up”和其他键也能按预期工作,那就太好了。
我该怎么做?
更新:
我看到了问题。 ScrolledPanel 能够滚动,但只有当它处于焦点下时。问题是,我如何才能成为焦点?即使点击它也不行。只有当我在其中放置一个文本控件时,我才能专注于它,从而用滚轮滚动。但我不想在其中包含文本控件。那么我该如何让它聚焦呢?
更新 2:
下面是一个代码示例,展示了这种现象。取消注释以查看文本控件如何使鼠标滚轮起作用。
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
# Uncomment the following 2 lines to see how adding
# a text control to the scrolled panel makes the
# mouse wheel work.
#
#text_control=wx.TextCtrl(scrolled_panel, -1)
#sizer.Add(text_control, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
#import cProfile; cProfile.run("app.MainLoop()")
app.MainLoop()
最佳答案
问题是窗口框架获得焦点而子面板没有获得焦点(在 ubuntu linux 上它工作正常)。解决方法可以像重定向 Frame 焦点事件以将焦点设置到面板一样简单,例如
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
self.panel.SetFocus()
scrolled_panel.Bind(wx.EVT_SET_FOCUS, self.onFocus)
def onFocus(self, event):
self.panel.SetFocus()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
app.MainLoop()
或 onmouse 移动到面板上,将焦点设置到它,所有键 + mousewheel 将开始工作,例如
import wx, wx.lib.scrolledpanel
class MyFrame(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = scrolled_panel = \
wx.lib.scrolledpanel.ScrolledPanel(parent=self, id=-1)
scrolled_panel.SetupScrolling()
scrolled_panel.Bind(wx.EVT_MOTION, self.onMouseMove)
text = "Ooga booga\n" * 50
static_text=wx.StaticText(scrolled_panel, -1, text)
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(static_text, wx.EXPAND, 0)
scrolled_panel.SetSizer(sizer)
self.Show()
def onMouseMove(self, event):
self.panel.SetFocus()
if __name__=="__main__":
app = wx.PySimpleApp()
my_frame=MyFrame(None, -1)
app.MainLoop()
关于python - 使用鼠标滚轮和箭头键滚动 `wx.ScrolledPanel`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1147581/