[Python] Use tkinter in an existing window

Discussão em 'Python' iniciado por Stack, Maio 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have an existing open window, created by SDL 2. I would like the process to call a python script to add some GUI elements to it.

    Here's a non-working example:

    import sys
    import sdl2
    import sdl2.ext

    import tkinter as tk
    from tkinter import *

    # Initialize SDL2
    sdl2.ext.init()

    # Set up the window
    window_width = 800
    window_height = 600
    window_title = "SDL2 Window"
    window = sdl2.ext.Window(window_title, size=(window_width, window_height))

    window.show()

    # Get SDL handle for the window
    wminfo = sdl2.SDL_SysWMinfo()
    sdl2.SDL_VERSION(wminfo.version)


    window_id = sdl2.SDL_GetWindowWMInfo(window.window, wminfo)
    print(wminfo.info.win.window)


    #tkinter
    The tkinter code examples mentioned below come here


    Looking at https://docs.python.org/3/library/tkinter.html#tkinter.Tk, I see that

    use Specifies the id of the window in which to embed the application, instead of it being created as an independent toplevel window.

    However, it also adds

    Note that on some platforms this will only work correctly if id refers to a Tk frame or toplevel that has its -container option enabled.

    Running the following prints a window id similar to window_id above.

    root = tk.Tk()
    tk_id = root.winfo_id()


    Running child = tk.Tk(use=str(wminfo.info.win.window)) causes python to exit without an exception. VS Code writes Server[1] disconnected unexpectedly but I don't think this is the X11 server but rather the debugger.

    Running root = tk.Tk() child = tk.Tk(use=str(tk_id)) causes python to exit as well.

    Can this be done at all? Am I missing something simple here?

    Continue reading...

Compartilhe esta Página