Search code examples
pythonwxpythonwxtextctrl

Get user input in WxPython


I want to make a program with a gui where you type something down into a text box and it does that task. A non gui example that I have is this:

input = input("");
def chat():
    if "hello" in input:
        print "hi"
while True:
    chat();

Obviously the code is longer, but the concept is the same. I also used espeak instead of print so a label won't be needed

Thanks!


Solution

  • Here's a simple example that does basically what you want:

    import wx
    
    ########################################################################
    class MyFrame(wx.Frame):
        """"""
    
        #----------------------------------------------------------------------
        def __init__(self):
            """Constructor"""
            wx.Frame.__init__(self, None, title="Chat")
            panel = wx.Panel(self)
    
            my_sizer = wx.BoxSizer(wx.VERTICAL)
    
            lbl = wx.StaticText(panel, label="Input:")
            my_sizer.Add(lbl, 0, wx.ALL, 5)
    
            self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER)
            self.txt.SetFocus()
            self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)
            my_sizer.Add(self.txt, 0, wx.ALL, 5)
    
            panel.SetSizer(my_sizer)
            self.Show()
    
        #----------------------------------------------------------------------
        def OnEnter(self, event):
            """"""
            text = self.txt.GetValue()
            if text.lower() == "hello":
                print "Hi!"
    
    if __name__ == "__main__":
        app = wx.App(True)
        frame = MyFrame()
        app.MainLoop()