Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Tkinter and Pygame can be integrated by embedding a Pygame surface in a Tkinter window.

Here's an example of how to do it:

  1. Import both modules:
import pygame
import tkinter as tk
  1. Initialize Pygame:
pygame.init()
  1. Create a Pygame surface:
screen = pygame.display.set_mode((640, 480))
  1. Create a Tkinter window and embed the Pygame surface:
root = tk.Tk()
embed = tk.Frame(root, width=640, height=480)
embed.pack()
embed.grid_propagate(False)
embed.grid(row=0, column=1)

os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
pygame.display.init()
pygame.display.update()
  1. Add a Pygame loop:
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Update Pygame surface
    pygame.display.update()
  1. Start the Tkinter main loop:
root.mainloop()

This will create a Pygame display that is embedded in a Tkinter window. You can then use Tkinter widgets to add GUI elements to control the Pygame surface.