使用KivyMD+多进程启动双窗口时出现XIO致命错误求助
Solution: Fix X Server Errors When Opening Multiple Kivy Windows via Multiprocessing
Root Cause
The error stems from Linux's default fork multiprocessing start method, which inherits the parent process's X11 display connection. X11 doesn’t allow multiple processes to share the same connection, leading to sequence number conflicts and fatal IO errors.
Step-by-Step Fix
- Use the
spawnstart method: This initializes each child process from scratch instead of inheriting the parent’s resources (including the X connection), eliminating conflicts. - Run independent Kivy/KivyMD Apps per process: Each process must create its own instance of an App subclass—never share widgets or app instances across processes.
- Isolate process UI contexts: Ensure each child process manages its own UI entirely, with no cross-process UI object sharing.
Corrected Pure Kivy Example
import multiprocessing from kivy.app import App from kivy.uix.label import Label def launch_window(window_title): class WindowApp(App): def build(self): self.title = window_title return Label(text=f"Window: {window_title}", font_size=24) WindowApp().run() if __name__ == '__main__': # Switch to spawn start method to avoid X connection inheritance multiprocessing.set_start_method('spawn') # Launch two separate windows proc1 = multiprocessing.Process(target=launch_window, args=("First Window",)) proc2 = multiprocessing.Process(target=launch_window, args=("Second Window",)) proc1.start() proc2.start() proc1.join() proc2.join()
KivyMD Adaptation
The same logic applies to KivyMD—each process runs its own independent MDApp instance:
import multiprocessing from kivymd.app import MDApp from kivymd.uix.label import MDLabel def launch_md_window(window_title): class MDWindowApp(MDApp): def build(self): self.title = window_title return MDLabel(text=f"KivyMD Window: {window_title}", halign="center", font_size=24) MDWindowApp().run() if __name__ == '__main__': multiprocessing.set_start_method('spawn') proc1 = multiprocessing.Process(target=launch_md_window, args=("MD Window 1",)) proc2 = multiprocessing.Process(target=launch_md_window, args=("MD Window 2",)) proc1.start() proc2.start() proc1.join() proc2.join()
Key Notes
- No cross-process UI sharing: Kivy/KivyMD UI objects are not designed to be shared between processes—each process must handle its own UI lifecycle.
spawnoverhead: This method has minor overhead compared tofork, but it’s mandatory for UI-related multiprocessing in Kivy on Linux.- DISPLAY variable: The
spawnmethod inherits the parent’s environment, so yourDISPLAYsetting (usually:0) will work automatically.
内容的提问来源于stack exchange,提问作者George Răbuș
相关产品推荐
相关产品推荐

