0

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
4

1 回答 1

1

如果您不回答 OK 则nameA不会设置。
例如,使用一个else子句给它一个替代值:

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'

或者在子句nameA之前给出一个默认值。if

编辑:
如前所述,您的代码中还有一些问题:

  1. 你需要调用ShowModal()它才能工作。
  2. 可能您想在阅读答案后关闭对话框。
  3. 也许您想为变量提供更充分/常规的名称

然后你将拥有:

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()
于 2013-03-08T22:35:26.557 回答