You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用wxPython编写Hello World程序时为何出现两个窗口?

Why Your wxPython Hello World Shows Two Windows (And How to Fix It)

Hey GregH, let's break down why you're seeing two windows pop up—this is one of the most common beginner pitfalls with wxPython, so you're definitely not alone!

Common Cause 1: Implicit Default Window + Custom Frame

The biggest culprit here is not overriding the OnInit() method when setting up your app. Let me explain:
When you create a wx.App() instance without customizing it, wxPython automatically generates a tiny, blank default top-level window behind the scenes. If you then manually create and show your own wx.Frame, you end up with two windows total.

Here's what that problematic code might look like:

import wx

# Creates the implicit default window
app = wx.App()
# Creates a second, intentional window
frame = wx.Frame(None, title="Hello World")
frame.Show()
app.MainLoop()

Fix: Override OnInit()

The correct approach is to subclass wx.App and override OnInit() to create your frame there. This tells wxPython to skip the default window and only use the one you define:

import wx

class MyHelloApp(wx.App):
    def OnInit(self):
        # Create and show your single frame here
        self.frame = wx.Frame(None, title="Hello World")
        self.frame.Show()
        # Return True to confirm initialization is complete
        return True

if __name__ == "__main__":
    app = MyHelloApp()
    app.MainLoop()

Common Cause 2: Accidental Duplicate Window Instantiation

Another easy mistake is creating two instances of your frame (or dialog) without realizing it. For example:

import wx

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="Hello World")
        self.Show()

if __name__ == "__main__":
    app = wx.App()
    frame1 = MyFrame()
    frame2 = MyFrame()  # Oops! This creates a second window
    app.MainLoop()

Fix: Check for Duplicate Code

Scan your code for any repeated lines where you instantiate your frame or top-level window. Remove the duplicate, and you'll only see one window.

Quick Troubleshooting Tip

If your screenshot shows one tiny blank window and one properly titled "Hello World" window, it's almost certainly the first issue (missing OnInit() override). If both windows look identical, you're probably instantiating your frame twice.

内容的提问来源于stack exchange,提问作者GregH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:06:23