如何在启动期间成功 运行 onButton?

How could I successfully run onButton during startup?

import wx

class MyForm(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Test")
        panel = wx.Panel(self, wx.ID_ANY)
        #Button is created; binded to onButton
        button = wx.Button(panel, id=wx.ID_ANY, label="Press Me")
        button.Bind(wx.EVT_BUTTON, self.onButton)

    def onButton(self,EVT_BUTTON):
        print("Hello world!")

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    #Runs Button command on startup
    MyForm.onButton()

I want onButton() to run at startup, and have it be able to run when the wx.Button is pressed. Unfortunetly, it comes up with this error: >TypeError: onButton() missing 2 required positional arguments: 'self' and 'EVT_BUTTON'

稍微难一点。我猜你是编程的初学者。如果是这样,我建议您学习更多基础知识。做 GUI 应用程序是一个更高级的主题。

所以,首先,对于你的 wxPython 程序 运行,你必须启动一个事件循环,所以你的程序应该有这样的东西:

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

您使用 2 个参数定义了函数 onButton。因此,您必须在调用函数时提供它们。第一个不是自我,就是框架。第二个被命名为EVT_BUTTON(并且给变量起这个名字表明你实际上并不理解这些概念,这就是我建议你从基础学习开始的原因)。

所以你可以打电话给

frame.OnButton(None)

在调用 app.MainLoop() 之前,代码将 运行。但这可能还不够。