【发布时间】:2015-07-21 10:15:31
【问题描述】:
我正在尝试在 wxPython 中显示图像网格。我正在使用 GridSizer 创建一个网格,并在其中添加我的静态位图。但由于某种原因,我只在网格的第一个位置看到一个图像。我不确定我哪里出错了。这是我的代码和相应的输出。
import wx
import sys
import glob
MAIN_PANEL = wx.NewId()
class CommunicationApp(wx.App):
"""This is the class for the communication tool application.
"""
def __init__(self, config=None, redirect=False):
"""Instantiates an application.
"""
wx.App.__init__(self, redirect=redirect)
self.cfg = config
self.mainframe = CommunicationFrame(config=config,
redirect=redirect)
self.mainframe.Show()
def OnInit(self):
# self.SetTopWindow(self.mainframe)
return True
class CommunicationFrame(wx.Frame):
"""Frame of the Communication Application.
"""
def __init__(self, config, redirect=False):
"""Initialize the frame.
"""
wx.Frame.__init__(self, parent=None,
title="CMC Communication Tool",
style=wx.DEFAULT_FRAME_STYLE)
self.imgs = glob.glob('../img/img*.png')
self.panel = CommuniationPanel(parent=self,
pid=MAIN_PANEL,
config=config)
# # Gridbagsizer.
nrows, ncols = 3, 4
self.grid = wx.GridSizer(rows=nrows, cols=ncols)
# Add images to the grid.
for r in xrange(nrows):
for c in xrange(ncols):
_n = ncols * r + c
_tmp = wx.Image(self.imgs[_n],
wx.BITMAP_TYPE_ANY)
_temp = wx.StaticBitmap(self.panel, wx.ID_ANY,
wx.BitmapFromImage(_tmp))
self.grid.Add(_temp, 0, wx.EXPAND)
self.grid.Fit(self)
# set to full screen.
# self.ShowFullScreen(not self.IsFullScreen(), 0)
class CommuniationPanel(wx.Panel):
"""Panel of the Communication application frame.
"""
def __init__(self, parent, pid, config):
"""Initialize the panel.
"""
wx.Panel.__init__(self, parent=parent, id=pid)
# CALLBACK BINDINGS
# Bind keyboard events.
self.Bind(wx.EVT_KEY_UP, self.on_key_up)
def on_key_up(self, evt):
"""Handles Key UP events.
"""
code = evt.GetKeyCode()
print code, wx.WXK_ESCAPE
if code == wx.WXK_ESCAPE:
sys.exit(0)
def main():
app = CommunicationApp()
app.MainLoop()
if __name__ == '__main__':
main()
这是输出。
我希望看到(或期望看到)的是不同图像的 3X4 网格。
我的代码有什么问题?我该如何解决?
【问题讨论】:
-
我没有尝试运行代码,但也许你忘了打电话给
SetSizer?self.panel.SetSizer(self.grid) -
@GP89 我知道这很简单但很重要,但我错过了。有效!感谢您的帮助。
-
没问题。我会将其作为答案发布,以防将来对其他人有所帮助
-
@siva82kb,使用 sys.exit 不是关闭应用程序的“好”方式,为什么不使用 parent.Close()?我还建议不要对主面板 ID 使用全局变量,我认为在当前的 wxPython 代码中,您几乎不需要保留/存储 ID。
-
@Werner 谢谢你的建议。我已经修改了我的代码。