i have code below. it put pygame screen to a customtkinter screen. but the pygame screen…
- User
i have code below. it put pygame screen to a customtkinter screen. but the pygame screen end up only occupy half of the customtkinter screen. can you identify why?
import pygame import customtkinter as ctk from tkinter import Frame from PIL import Image, ImageTk
Initialize Pygame
pygame.init()
Function to update the Pygame surface and embed it in the Tkinter canvas
def update_pygame_surface(event=None): global screen, image_tk # Get the current size of the Tkinter window window_width = root.winfo_width() window_height = root.winfo_height()
# Create a new Pygame display surface with the same size as the Tkinter window screen = pygame.display.set_mode((window_width, window_height), pygame.HIDDEN) screen.fill((0, 0, 0)) # Fill the screen with black pygame.display.flip() # Update the display # Convert the Pygame surface to a PIL Image image_data = pygame.surfarray.array3d(screen) image_pil = Image.fromarray(image_data) # Convert the PIL Image to a Tkinter PhotoImage image_tk = ImageTk.PhotoImage(image_pil) # Update the canvas to display the new image canvas.delete("all") # Clear the canvas canvas.create_image(0, 0, anchor='nw', image=image_tk)Initialize CustomTkinter
root = ctk.CTk() root.title("Pygame in CustomTkinter")
Set the initial size of the window
root.geometry("1366x768")
Create a frame to hold the Pygame surface
frame = Frame(root) frame.pack(fill='both', expand=True)
Embed the Pygame surface into the Tkinter frame
canvas = ctk.CTkCanvas(frame) canvas.pack(fill='both', expand=True)
Bind the update function to the window resize event
root.bind("", update_pygame_surface)
Initialize the Pygame surface for the first time
update_pygame_surface()
Run the Tkinter event loop
root.mainloop()
- Assistant