【问题标题】:AttributeError: 'Window' object has no attribute 'pressed'AttributeError:“窗口”对象没有“按下”属性
【发布时间】:2021-11-08 19:48:55
【问题描述】:

我已经尝试删除pressed() 中的事件参数并移动pressed() 的位置,但没有任何效果......我很卡住。

我尝试过的代码:

import wx

class Window ( wx.Frame ):
    def __init__ ( self ):
        super().__init__ ( parent = None, title = "Hello World!" )
        
        panel = wx.Panel ( self )
        sizer = wx.BoxSizer ( wx.VERTICAL )
        
        self.TextBox = wx.TextCtrl ( panel, pos = ( 5, 5 ), style = wx.TE_MULTILINE | wx.TE_AUTO_URL )
        sizer.Add ( self.TextBox, 0, wx.ALL | wx.EXPAND, 5 )
        
        self.button = wx.Button ( panel, label = "Button", pos = ( 5, 40 ) )
        self.button.Bind ( wx.EVT_BUTTON, self.pressed )
        sizer.Add ( self.button, 0, wx.ALL | wx.CENTER, 5 )
        
        def pressed ( self, event ):
            text = self.TextBox.GetValue()
            print ( text )
        
        panel.SetSizer ( sizer )
        self.Show()

if __name__ == '__main__':
    app = wx.App()
    window = Window()
    app.MainLoop()

错误:

Traceback (most recent call last):

  File "E:\Dell\Python\WxPython.py", line 27, in <module>
    window = Window()

  File "E:\Dell\Python\WxPython.py", line 15, in __init__
    self.button.Bind ( wx.EVT_BUTTON, self.pressed )

AttributeError: 'Window' object has no attribute 'pressed'

【问题讨论】:

    标签: python wxpython


    【解决方案1】:

    您按下的方法过度缩进。它必须与 init 处于同一级别。否则它将是 init 的本地函数,仅在 init 中可见,并且在 self.button.Bind 调用后实际上有效。

    import wx
    
    class Window ( wx.Frame ):
        def __init__ ( self ):
            super().__init__ ( parent = None, title = "Hello World!" )
    
            panel = wx.Panel ( self )
            sizer = wx.BoxSizer ( wx.VERTICAL )
    
            self.TextBox = wx.TextCtrl ( panel, pos = ( 5, 5 ), style = wx.TE_MULTILINE | wx.TE_AUTO_URL )
            sizer.Add ( self.TextBox, 0, wx.ALL | wx.EXPAND, 5 )
    
            self.button = wx.Button ( panel, label = "Button", pos = ( 5, 40 ) )
            self.button.Bind ( wx.EVT_BUTTON, self.pressed )
            sizer.Add ( self.button, 0, wx.ALL | wx.CENTER, 5 )
    
            panel.SetSizer ( sizer )
            self.Show()
    
        def pressed ( self, event ):
            text = self.TextBox.GetValue()
            print ( text )
    
    
    if __name__ == '__main__':
        app = wx.App()
        window = Window()
        app.MainLoop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-31
      • 2020-01-18
      • 2012-12-01
      • 2021-04-19
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多