我如何使用wxpython

时间:2019-07-16 15:15:03

标签: python-3.x wxpython

我需要知道如何像其他面板中的板一样读取和显示矩阵5x5(5行,5列)的矩形块内的​​所有像素的值

我做这个例子只是为了解释我需要做的事情:

我需要在paneltwo中显示的内容类似于此示例:

enter image description here

该代码:

import wx
import numpy as np
import netCDF4
from netCDF4 import Dataset
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.patches as patches
import matplotlib

class Window(wx.Frame):


    def __init__(self, **kwargs):
        super().__init__(None, **kwargs)
        RootPanel(self)

class RootPanel(wx.Panel):


    def __init__(self, parent):
        super().__init__(parent)

        panel_buttons = wx.Panel(self)
        panel_buttons_sizer = wx.GridSizer(1, 2, 0, 0)

        self.canvas_panel = CanvasPanel(self)
        self.panel_two = PanelTwo(parent=self)

        select_button = PickButton(
            panel_buttons,
            "netCDF4 files (nc)|*.nc",
            self.canvas_panel.load_from_file,
            label="Show on this window (nc)",
        )
        toplevel_select_button = TopLevelPickButton(
            panel_buttons,
            "Text files (txt)|*.txt|All files|*.*",
            label="Show on separate window (txt)",
        )
        panel_buttons_sizer.Add(select_button)
        panel_buttons_sizer.Add(toplevel_select_button)
        panel_buttons.SetSizer(panel_buttons_sizer)

        canvas_sizer = wx.BoxSizer(wx.HORIZONTAL)
        canvas_sizer.Add(self.canvas_panel,1,wx.EXPAND)
        canvas_sizer.Add(self.panel_two,1,wx.EXPAND)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(panel_buttons)
        sizer.Add(canvas_sizer)
        self.SetSizerAndFit(sizer)
        self.Show()

class PickButton(wx.Button):


    def __init__(self, parent, wildcard, func, **kwargs):

        super().__init__(parent, **kwargs)
        self.wildcard = wildcard
        self.func = func
        self.Bind(wx.EVT_BUTTON, self.pick_file)

    def pick_file(self, evt):
        style = style = wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE
        with wx.FileDialog(
            self, "Pick files", wildcard=self.wildcard, style=style
        ) as fileDialog:
            if fileDialog.ShowModal() != wx.ID_CANCEL:
                chosen_file = fileDialog.GetPath()
                self.func(chosen_file)

class TopLevelPickButton(PickButton):


    def __init__(self, parent, wildcard, **kwargs):
        super().__init__(parent, wildcard, self.create_toplevel, **kwargs)

    def create_toplevel(self, file_name):
        """ Ouvre une toplevel et affiche le graphique """
        self.win = TopLevelCanvas(self.Parent)
        self.win.canvas_panel.load_from_file(file_name)
        self.win.Show()

class CanvasPanel(wx.Panel):
    """ Panel du graphique matplotlib """
    def __init__(self, parent , size=(200,250)):
        super().__init__(parent)
        self.figure = Figure(figsize =(5,5))
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.Size = self.canvas.Size
        self.parent = parent

    def load_from_file(self, file_name):

        self.axes = self.figure.add_subplot(111)
        if file_name.endswith(".nc"):
            self._load_nc(file_name)
        else:
            self._load_txt(file_name)
        self.canvas.draw()

    def _load_txt(self, file_name):
        self._load_nc(file_name)

    def _load_nc(self, file_name):

        fic='air.departure.sig995.2012.nc'

        path='D:/data/'


        nc = netCDF4.Dataset(path+fic,'r')
        lons = nc.variables['lon'][:]
        lats = nc.variables['lat'][:]
        air_dep = nc.variables['air_dep'][:,:,:]
        air_dep = air_dep[0,:,:]


        self.axes.imshow(air_dep)

        self.canvas.mpl_connect('button_press_event', self.on_press)
        x = y = 1
        self.rect = patches.Rectangle((x, y), 5,5,edgecolor='r', alpha=1, fill=None, label='Label')
        self.axes.add_patch(self.rect)
        self.axes.plot()
        self.Show()

    def on_press(self, click):
        x1, y1 = click.xdata, click.ydata
        self.parent.panel_two.Update(x1,y1)
        zx1 = x1 - 2.5
        zy1 = y1 - 2.5
        zx2 = x1 + 2.5
        zy2 = y1 + 2.5
        self.rect.set_x(x1 - 2.5) #Move the rectangle and centre it on the X click point
        self.rect.set_y(y1 - 2.5) #Move the rectangle and centre it on the Y click point


        self.axes.plot()
        self.canvas.draw()



class PanelTwo(wx.Panel): #here when i need to visualize pixel and coordinator cursor
    def __init__(self,parent):
        wx.Panel.__init__(self,parent,size=(300,250))

        self.text_ctrl = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.BORDER_SUNKEN|wx.TE_READONLY|wx.TE_RICH2, size=(200,170))

        lbl = wx.StaticText(self,label="Coordinato cursor & Pixel ")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(lbl,0, wx.ALIGN_CENTRE,10)
        sizer.Add(self.text_ctrl,0, wx.ALIGN_CENTRE,10)
        self.SetSizer(sizer)

    def Update(self,x1,y1):
        self.text_ctrl.SetValue("Mouse click at;\nX "+str(x1)+"\nY "+str(y1))



class TopLevelCanvas(wx.Frame):


    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)
        self.canvas_panel = CanvasPanel(self)
        self.zoom_panel = Zoom(parent=self)
        self.Size = self.canvas_panel.Size
        canvas_sizer = wx.BoxSizer(wx.HORIZONTAL)
        canvas_sizer.Add(self.canvas_panel,1,wx.EXPAND)
        canvas_sizer.Add(self.zoom_panel,1,wx.EXPAND)
        self.SetSizerAndFit(canvas_sizer)
        self.Show()

class App(wx.App):
    def OnInit(self):
        win = Window(title="A test dialog", size=(1000, 800))
        win.Show()
        return True

if __name__ == "__main__":
    app = App()
    app.MainLoop()

也许我需要在此代码行中使用类似**air_dep[x-5:x+5,y-5:y+5]**的东西:

def on_press(self, click):
            x1, y1 = click.xdata, click.ydata
            self.parent.panel_two.Update(x1,y1)

我如何在所有列和行的示例中显示矩阵或木板等值?

enter image description here

谢谢

其他文件netcdf4:https://drive.google.com/open?id=1IT-F7AbIx4bCjMLosjBx4F4UCoIX5DU0 here

1 个答案:

答案 0 :(得分:2)

当前5x5网格已写入第二个面板,您可以为它们创建一个单独的面板。
5x5网格有点怪异,因为在边缘周围网格可以变成3x5或5x3,在角落处必须变成3x3。

const assert = require('assert'),
    request = require('supertest'),
    app = require('../app'),
    superagent = require('superagent')

describe('Testing the api/product POST route', function() {

    let token = null;
    const credentials = {
        email: 'test@test.com',
        password: 'test'
    }

    before(function() {
        superagent
            .post('http://localhost:3000/api/users/login')
            .send(credentials) // sends a JSON post body
            .set('Content-Type', 'application/json')
            .end((err, res) => {
                if (err) {
                    console.log(err)
                    return
                }
                token = res.body.token
            });
    }),

    it('should return 422 status when you send an empty product object', function() {
        request(app)
            .post('/api/products')
            .send({})
            .set('Content-Type', 'application/json')
            .set('Authorization', 'Bearer ' + token)
            .then((res) => {
                console.log(res)
                assert.equal(1, 1)
            })
    })
})

enter image description here