Search code examples
pythondialogwxpythonpyserial

How to hide wx.Dialog(why .Hide() doesnt work)?


My question is how can I hide wx.Dialog when press OK? I tried

wx.Dialog.Destroy(),

wx.Dialog.Close() and

wx.Dialog.Hide()

All of them shut my wx.Dialog down. I'm trying to press OK and then open the frame or panel (I definetely need to close the dialog. Otherwise in dialog i can open the frame/panel).

It would be really appreciated.

def OnOK(self, event):
    global ser
    success = True
    self.serial.port = self.ports[self.choice_port.GetSelection()]                 
    if self.show & SHOW_BAUDRATE: 
        try: 
            b = int(self.combo_box_baudrate.GetValue()) 
        except ValueError: 
            with wx.MessageDialog(self, 'Baudrate must be a numeric value', 'Value Error', wx.OK | wx.ICON_ERROR) as dlg:
                dlg.ShowModal()   
            success = False          
        else: 
            self.serial.baudrate = b

    a = self.serial.port
    b = self.serial.baudrate
    ser = serial.Serial('{}'.format(a),'{}'.format(b)) 
    print(a,b) 

    #self.connected=True

    if success:
        self.EndModal(wx.ID_OK)
        #wx.Dialog.Destroy(self)
        #wx.Dialog.Close(self)  
        #wx.Dialog.Hide(self) 

If necessary, whole code is:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import wx
import serial
import serial.tools.list_ports

SHOW_BAUDRATE = 1 << 0
SHOW_FORMAT = 1 << 1 
SHOW_ALL = SHOW_BAUDRATE | SHOW_FORMAT 
class SerialConfigDialog(wx.Dialog):

    def __init__(self, parent, *args, **kwds):
        self.serial = kwds['serial']
        del kwds['serial']
        self.show = SHOW_ALL
        if 'show' in kwds:
            self.show = kwds.pop('show')
        kwds["style"] = wx.DEFAULT_DIALOG_STYLE


        wx.Dialog.__init__(self, parent, size = ( 700,500 ),*args, **kwds)
        #wx.Frame.__init__(self, parent, *args, **kwds)
        #Dialog(parent, id=ID_ANY, title="", pos=DefaultPosition, size=DefaultSize, style=DEFAULT_DIALOG_STYLE, name=DialogNameStr)

        self.label_2 = wx.StaticText(self, -1, "Port")
        self.choice_port = wx.Choice(self, -1, choices=[])
        self.label_1 = wx.StaticText(self, -1, "Baudrate")
        self.combo_box_baudrate = wx.ComboBox(self, -1, choices=[], style=wx.CB_DROPDOWN)
        self.sizer_1_staticbox = wx.StaticBox(self, -1, "Basics")
        self.button_ok = wx.Button(self, wx.ID_OK, "")
        self.button_cancel = wx.Button(self, wx.ID_CANCEL, "")
        #self.__set_properties()
        #self.__do_layout()
        #self.__attach_events()

    #def __set_properties(self):
        self.SetTitle("Serial Port Configuration")
        self.button_ok.SetDefault()
        self.SetTitle("Serial Port Configuration")
        self.button_ok.SetDefault()
        preferred_index = 0
        self.choice_port.Clear()
        self.ports = []
        self.connected = False
        for n, (portname, desc, hwid) in enumerate(sorted(serial.tools.list_ports.comports())):
            self.choice_port.Append(u'{} - {}'.format(portname, desc))
            self.ports.append(portname)
            if self.serial.name == portname:
                preferred_index = n
        self.choice_port.SetSelection(preferred_index)
        if self.show & SHOW_BAUDRATE:
            preferred_index = None
            self.combo_box_baudrate.Clear()
            for n, baudrate in enumerate(self.serial.BAUDRATES):
                self.combo_box_baudrate.Append(str(baudrate))
                if self.serial.baudrate == baudrate:
                    preferred_index = n
            if preferred_index is not None:
                self.combo_box_baudrate.SetSelection(preferred_index)
            else:
                self.combo_box_baudrate.SetValue(u'{}'.format(self.serial.baudrate))

    #def __do_layout(self):
        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
        grid_sizer_1 = wx.FlexGridSizer(3, 2, 0, 0)
        self.sizer_1_staticbox.Lower()
        sizer_1 = wx.StaticBoxSizer(self.sizer_1_staticbox, wx.VERTICAL)

        sizer_basics = wx.FlexGridSizer(3, 2, 0, 0)
        sizer_basics.Add(self.label_2, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        sizer_basics.Add(self.choice_port, 0, wx.EXPAND, 0)
        sizer_basics.Add(self.label_1, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        sizer_basics.Add(self.combo_box_baudrate, 0, wx.EXPAND, 0)
        sizer_basics.AddGrowableCol(1)

        sizer_1.Add(sizer_basics, 0, wx.EXPAND, 0)
        sizer_2.Add(sizer_1, 0, wx.EXPAND, 0)
        sizer_3.Add(self.button_ok, 0, 0, 0)
        sizer_3.Add(self.button_cancel, 0, 0, 0)
        self.m_button26 = wx.Button( self, wx.ID_ANY, u"Back", wx.DefaultPosition, wx.DefaultSize, 0 )
        sizer_3.Add( self.m_button26, 0, 0, 0 )
        sizer_2.Add(sizer_3, 0, wx.ALL | wx.ALIGN_RIGHT, 4)

        self.SetSizer(sizer_2)
        #sizer_2.Fit(self)  ### for no-resize
        self.Layout()

    #def __attach_events(self):
        wx.EVT_BUTTON(self, self.button_ok.GetId(), self.OnOK)
        wx.EVT_BUTTON(self, self.button_cancel.GetId(), self.OnCancel)
        self.m_button26.Bind( wx.EVT_BUTTON, self.back__f )

    def OnOK(self, event):
        global ser
        success = True
        self.serial.port = self.ports[self.choice_port.GetSelection()]                 
        if self.show & SHOW_BAUDRATE: 
            try: 
                b = int(self.combo_box_baudrate.GetValue()) 
            except ValueError: 
                with wx.MessageDialog(self, 'Baudrate must be a numeric value', 'Value Error', wx.OK | wx.ICON_ERROR) as dlg:
                    dlg.ShowModal()   
                success = False          
            else: 
                self.serial.baudrate = b

        a = self.serial.port
        b = self.serial.baudrate
        ser = serial.Serial('{}'.format(a),'{}'.format(b)) 
        print(a,b) 

        #self.connected=True

        if success:
            print("1")
            #self.EndModal(wx.ID_OK)
            wx.Dialog.Hide(self)

            #wx.Dialog.Destroy(self)
            #wx.Dialog.Close(self)  
            #wx.Dialog.Hide(self) 


    def OnCancel(self, events):
        self.EndModal(wx.ID_CANCEL)

    def back__f( self, event ):        
        self.a = MyFrame4( self )
        self.a.Show()

class MyApp(wx.App):

    def OnInit(self):
        wx.InitAllImageHandlers()
        ser = serial.Serial()
        for flags in (SHOW_BAUDRATE, SHOW_FORMAT, SHOW_ALL):
            dialog_serial_cfg = SerialConfigDialog(None, -1, "", serial=ser, show=flags)

            self.SetTopWindow(dialog_serial_cfg)
            result = dialog_serial_cfg.ShowModal()

            if result != wx.ID_OK:
                break 
        return 0     


if __name__ == "__main__": 
    app = MyApp(0)
    app.MainLoop() 

Solution

  • You need to use self.Destroy() inside your wx.Dialog subclass. You do not call wx.Dialog.Destroy or any of the other methods directly. Instead, you must always use self.MethodName()