Embedding a Pygame window into a Tkinter or WxPython frame

后端 未结 3 1781
Happy的楠姐
Happy的楠姐 2020-11-28 08:01

A friend and I are making a game in pygame. We would like to have a pygame window embedded into a tkinter or WxPython frame, so that we can include text input, buttons, and

相关标签:
3条回答
  • 2020-11-28 08:42

    According to the tracebacks, the program crashes due to TclErrors. These are caused by attempting to access the same file, socket, or similar resource in two different threads at the same time. In this case, I believe it is a conflict of screen resources within threads. However, this is not, in fact, due to an internal issue that arises with two gui programs that are meant to function autonomously. The errors are a product of a separate thread calling root.update() when it doesn't need to because the main thread has taken over. This is stopped simply by making the thread call root.update() only when the main thread is not doing so.

    0 讨论(0)
  • 2020-11-28 08:57

    According to this SO question and the accepted answer, the simplest way to do this would be to use an SDL drawing frame.

    This code is the work of SO user Alex Sallons.

    import pygame
    import Tkinter as tk
    from Tkinter import *
    import os
    
    root = tk.Tk()
    embed = tk.Frame(root, width = 500, height = 500) #creates embed frame for pygame window
    embed.grid(columnspan = (600), rowspan = 500) # Adds grid
    embed.pack(side = LEFT) #packs window to the left
    buttonwin = tk.Frame(root, width = 75, height = 500)
    buttonwin.pack(side = LEFT)
    os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
    os.environ['SDL_VIDEODRIVER'] = 'windib'
    screen = pygame.display.set_mode((500,500))
    screen.fill(pygame.Color(255,255,255))
    pygame.display.init()
    pygame.display.update()
    def draw():
        pygame.draw.circle(screen, (0,0,0), (250,250), 125)
        pygame.display.update()
        button1 = Button(buttonwin,text = 'Draw',  command=draw)
        button1.pack(side=LEFT)
        root.update()
    
    while True:
        pygame.display.update()
        root.update()      
    

    This code is cross-platform, as long as the windb SDL_VIDEODRIVER line is omitted on non Windows systems. I would suggest

    # [...]
    import platform
    if platform.system == "Windows":
        os.environ['SDL_VIDEODRIVER'] = 'windib'
    # [...]
    
    0 讨论(0)
  • 2020-11-28 09:02

    Here are some links.

    • For embedding in WxPython An Article on pygame.org
    • For Embedding in WxPython An Article on the WxPython wiki
    • For embedding in Tkinter see this SO question

    Basically, there are many approaches.

    • On Linux, you can easily embed any application in a frame inside another. Simple.
    • Direct Pygame output to a WkPython Canvas

    Some research will provide the relevant code.

    0 讨论(0)
提交回复
热议问题