Taylor
Taylor

Reputation: 51

wxpython textentrydialog won't appear

I am following a tutorial to try to learn to use Wxpython, so I do not fully understand what is going on yet, but when I run the following code it seems like a text dialog box should appear and ask me for my name, however the dialog box does not appear and thus the nameA variable is not assigned a value so I get the error below. What am I doing wrong?

Python Program:

import wx

class main(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Test Window", size = (300, 200))
        panel = wx.Panel(self)

        text= wx.TextEntryDialog(None, "What is your name?", "Title", " ")
        if text.ShowModal == wx.ID_OK:
            nameA = text.GetValue()

        wx.StaticText(panel, -1, nameA, (10, 10))


if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = main(parent=None, id= -1)
    frame.Show()
    app.MainLoop()

The error I recieve:

Traceback (most recent call last):
  File "C:\Users\Taylor Lunt\Desktop\deleteme.py", line 17, in <module>
    frame = main(parent=None, id= -1)
  File "C:\Users\Taylor Lunt\Desktop\deleteme.py", line 12, in __init__
    wx.StaticText(panel, -1, nameA, (10, 10))
UnboundLocalError: local variable 'nameA' referenced before assignment

Upvotes: 0

Views: 1157

Answers (1)

joaquin
joaquin

Reputation: 85603

If you do not answer OK then nameA will not be set.
Use for example an else clause to give it an alternate value:

text= wx.TextEntryDialog(None, "What is your name?", "Title", " ")
if text.ShowModal == wx.ID_OK:         # this is not correct. see edit
    nameA = text.GetValue()
else:
    nameA = 'Nothing'

or give nameA a default value before the if clause.

Edit:
As indicated there are some more problems in your code:

  1. You need to call ShowModal() for it to work.
  2. Probably you want to close your dialog after reading the answer.
  3. Maybe you want to give more adequate/conventional names for your variables

Then you will have:

dlg = wx.TextEntryDialog(None, "What is your name?", "Title", " ")

answer = dlg.ShowModal()

if answer == wx.ID_OK:
    nameA = dlg.GetValue()
else:
    nameA = 'Nothing'

dlg.Destroy()

Upvotes: 1

Related Questions