如何将变量从一个函数调用到另一个函数?

2024-05-14 01:15:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在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

Tags: 实例函数selfeventinitdefargscall
1条回答
网友
1楼 · 发布于 2024-05-14 01:15:07

欢迎使用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 functionspartial module的用法。你知道吗

相关问题 更多 >