我正在按照教程尝试学习使用Wxpython,所以我还没有完全理解发生了什么,但是当我运行以下代码时,似乎应该出现一个文本对话框并询问我的名字,但是没有出现对话框,因此nameA变量没有赋值,所以我得到下面的错误。我做错了什么?
Python程序:
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()
我收到的错误:
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
答案 0 :(得分:1)
如果您没有回答确定,则不会设置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
一个默认值。
编辑:
如上所示,您的代码中还有一些问题:
ShowModal()
才能使其正常工作。然后你会:
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()