在 wxPython 中,我试图从一个函数(在实例化器中)定义一个变量以调用另一个函数(不在实例化器中,但仍在类中)
我见过人们在他们的情况下解决其他人的问题,我也尝试过其他人,但它对我不起作用。
class NamePrompts(wx.Frame):
def __init__(self, *args, **kw):
super(NamePrompts, self).__init__(*args, **kw)
panl = wx.Panel(self)
textboxtest = wx.TextCtrl(panl) # defining textboxtest as a text box
textboxtest.Bind(wx.EVT_TEXT, self.OnKeyTyped)
read = wx.Button(panl, label="Print", pos=(0, 25))
read.Bind(wx.EVT_BUTTON, self.PrintText)
def PrintText(self, event):
typedtext = event.textboxtest.GetString() # attempting to call the same textbox here
wx.StaticText(wx.Panel(self), label=typedtext, pos=(25, 25))
if __name__ == '__main__':
app = wx.App()
frm = NamePrompts(None, title='Basketball Game')
frm.SetSize(0,0,1920,1040)
frm.Show()
app.MainLoop()
我收到这个错误:
AttributeError: 'CommandEvent' object has no attribute 'textboxtest'
Traceback (most recent call last):
File "textboxtest.py", line 19, in PrintText
typedtest = event.textboxtest.GetString() # attempting to call the same text box here
请您参考如下方法:
欢迎使用 StackOverflow。
实现你想要的最简单的方法是在创建 wx.TextCtrl 时使用 self 所以它可以从 __init__ 以外的方法获得> 然后直接从其他方法访问 wx.TextCtrl 的值。
import wx
class NamePrompts(wx.Frame):
def __init__(self, *args, **kw):
super(NamePrompts, self).__init__(*args, **kw)
panl = wx.Panel(self)
self.textboxtest = wx.TextCtrl(panl) # defining textboxtest as a text box
#self.textboxtest.Bind(wx.EVT_TEXT, self.OnKeyTyped)
read = wx.Button(panl, label="Print", pos=(0, 25))
read.Bind(wx.EVT_BUTTON, self.PrintText)
def PrintText(self, event):
typedtext = self.textboxtest.GetValue() # attempting to call the same textbox here
print(typedtext)
wx.StaticText(wx.Panel(self), label=typedtext, pos=(25, 25))
if __name__ == '__main__':
app = wx.App()
frm = NamePrompts(None, title='Basketball Game')
frm.SetSize(50,50,300,300)
frm.Show()
app.MainLoop()
不过,如果您想了解如何通过事件传递自定义变量,您可以查看 lambda functions 的用法。和 partial module .
