How to make a fully transparent window with PyGame ?
Last Updated :
04 Jan, 2023
Fully transparent windows with PyGame have their own advantage while building many games and apps via Python. Thus in order to achieve the functionality of the transparent window that allows the user to see behind a running screen.
For example:
Geek want to design an app, in which they can see the background screen of the other windows. Thus in order to achieve this, he can use PyGame libraries and windows libraries of Python.
Required modules and Libraries:
pip install pygame
pip install pywin32api
pip install win32con
pip install win32gui
Stepwise Implementation:
Step 1: Import all the required files, libraries, and modules.
Python3
import pygame as py
import win32api
import win32con
import win32gui
|
Step 2: Initialize the PyGame module and libraries. And declare the PyGame window screen. With the mode of the desired window size. And declaring the windows graphical user interface.
Python3
py.init()
window_screen = py.display.set_mode(( 700 , 450 ))
hwnd = py.display.get_wm_info()[ "window" ]
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, win32gui.GetWindowLong(
hwnd, win32con.GWL_EXSTYLE) | win32con.WS_EX_LAYERED)
|
Step 3: Set window transparency color and the text to be displayed on the current window of PyGame. In this, we will be also using the “hwnd” variable that we have created in step2. Declare the font color and size for the font.
Python3
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB( 255 , 0 , 128 ), 0 , win32con.LWA_COLORKEY)
font = py.font.SysFont( "Times New Roman" , 54 )
text = []
text.append((font.render( "Transparent Window" , 0 , ( 255 , 100 , 0 )), ( 20 , 10 )))
text.append((font.render( "Press Esc to close the window" , 0 , ( 255 , 100 , 100 )), ( 20 , 250 )))
|
Step 4: Now we will create a function that will display the text we want in our window.
Python3
def show_text():
for t in text:
window_screen.blit(t[ 0 ], t[ 1 ])
|
Step 5: Main while loop that will run the program and make the PyGame window active till the escape button or the cross button is pressed. Fill the PyGame window with the transparent color declared above. And calling the show_text() function.
Python3
done = 0
while not done:
for event in py.event.get():
if event. type = = py.QUIT:
done = 1
if event. type = = py.KEYDOWN:
if event.key = = py.K_ESCAPE:
done = 1
window_screen.fill(( 255 , 0 , 128 ))
show_text()
py.display.update()
|
Output:
Fully transparent window with PyGame.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...