Changing desktop background and playing .mp3 file is not working - python

import ctypes
import winsound
SPI_SETDESKWALLPAPER = 20
while (True):
x = input("Enter Password. ")
if x == "blyat":
print ("motherland russia")
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, "D:\\VS Code Project\\COMMUNISM.jpg", 0)
winsound.PlaySound("USSR Anthem.mp3", winsound.SND_FILENAME)
When I run the program, I can't hear the .mp3 and the desktop background goes black instead of changing to the image I selected (COMMUNISM.jpg)

Based on the information you provided, I did the following:
Install the module "playsound" and add it to use: (pip install playsound)
from playsound import playsound
Use "playsound('D:\\...\\Ze\\1.mp3')" instead of "winsound.PlaySound("D:\\...\\Ze\\1.mp3", winsound.SND_FILENAME)"
Complete code:
from playsound import playsound
import ctypes
import winsound
SPI_SETDESKWALLPAPER = 20
while (True):
x = input("Enter Password:")
if x == "blyat":
print ("motherland russia")
ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, "D:\\...\\Ze\\1.jpg", 0)
# winsound.PlaySound("D:\\...\\Ze\\1.mp3", winsound.SND_FILENAME)
playsound('D:\\...\\Ze\\1.mp3')
The result of my test on my computer is that the desktop wallpaper was changed and the mp3 played.

Related

ModuleNotFoundError: No module named 'playsound' what to do?

I've been editing this mp3 player, but this error keeps apearing
from tkinter import *
from tkinter import messagebox
import playsound
#making the window
window = Tk()
window.title("button")
window.geometry("350x450+500+200")
#making the song fuction
def song():
playsound ("lights.mp3")
# making texbox
def InitialMessage():
name = name_Tf.get()
mood = mood_Tf.get()
#mood happy
if mood == "happy":
return messagebox.showinfo("message",
f"""Hi! {name}, wellcome.
may I intrest you with some music?""",
#making the song executer
button1 = Button(messagebox,
text="yes",
command=song,
font= ("Comic Sans", 15 )))
I don't have python 2 on the pc anymore, I uninstalled it, I have tried reinstaling playsound, as well as change the interpreter to the recomended, I dunno what to do anymore, please help
Try importing playsound with PIP
pip install playsound
And include in your code
from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')

Why is pyAutoGui not clicking in certain windows

I'm trying to make a python program to Automate the setup of a new computer. I used pyAutoGui to click on the Install button when prompted but it wont click on the button. It detects the image "Install.png" because it breaks the while loop when Adobe prompts to install. I tested it in paint and if I change the Install.png image to something on paint I can visually see it clicks. I tried the mouse library, moving it to the coordinates and then clicking, double- tripleClick, MouseDown -> sleep -> MouseUp, just MouseDown -> MouseUp, sending enter with pyAutogui, sending enter with shell, using subprocess and some other stuff. Nothing seems to work on the popup window Adobe gives. I printed the coordinates and they come out fine (I used DisplayMouseInfo to see of the coordinates were correct) I even hard coded the coordinates but it doesnt click install. Any answers would be appreciated, here is how it looks.
import os
import shutil
import subprocess
import psutil
import pyautogui as pg
import time
global path
path = os.getcwd()
def adobe_install():
adobe_setup_path = os.path.join(path, "Adobe.exe")
adobe_cmd = str("start " + adobe_setup_path)
os.system(adobe_cmd)
while pg.locateCenterOnScreen('Install.png', confidence=0.9) == None:
wait
time.sleep(2)
clk= pg.locateCenterOnScreen('Install.png', confidence=0.9)
pg.click(clk.x, clk.y)
EDIT
I tried the following
Install is just the a screenshot of the install button and the coordinates it prints (clk.x ; clk.y) are correct
import os
import shutil
import subprocess
import pyautogui as pg
import time
import pathlib
import winreg
import win32con
import win32gui
def adobe_install():
adobe_setup_path = os.path.join(path, "Adobe.exe")
adobe_cmd = str("start " + adobe_setup_path)
os.system(adobe_cmd)
while pg.locateCenterOnScreen('Install.png', confidence=0.9) == None:
wait
results = []
top_windows = []
win32gui.EnumWindows(windowEnumerationHandler, top_windows)
for i in top_windows:
if "Adobe Acrobat Reader DC (Continuous) - Setup" in i[1]:
print(i)
win32gui.ShowWindow(i[0],5)
win32gui.SetForegroundWindow(i[0])
bring_to_front(i[0])
break
time.sleep(2)
clk= pg.locateCenterOnScreen('Install.png', confidence=0.9)
print(clk.x)
print(clk.y)
pg.click(clk.x, clk.y)
pg.leftClick(x=clk.x, y=clk.y)
pg.typewrite(['enter'], interval=1)
adobe_install()
I tried clicking, left clicking, and pressing enter. I tested the in other windows like Paint and word and the clicking and they all did indeed click or send "Enter"
This is the error I recieved
File "C:\Users\***\documents\ict\software\New_comp.py", line 77, in adobe_install
bring_to_front(i[0])
File "C:\Users\***\documents\ict\software\New_comp.py", line 41, in bring_to_front
win32gui.SetWindowPos(HWND, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
pywintypes.error: (5, 'SetWindowPos', 'Access is denied.')
Try bringing the window to front & activate it. But you need to put in the window handler
import win32gui
import win32con
def bringTOfront(HWND):
win32gui.ShowWindow(HWND, win32con.SW_RESTORE)
win32gui.SetWindowPos(HWND, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
win32gui.SetWindowPos(HWND, win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
win32gui.SetWindowPos(HWND, win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)

How to get the screenshot of a tkinter window

I am trying to build a program which gets me an enlarged photo of the text I want, for this I decided to use tkinter, win32gui and pygetwindow modules after taking some tips from already asked problems on stack overflow am having the following problems:
(1)I don't know how to get the hwnd value of the tkinter window which I created.
(2)I can't get hwnd value even if I know how to get it as the window is created after the complete code has run.
So please suggest me solutions to the problem
This is my code:
from tkinter import *
import win32gui
import pygetwindow as gw
#making the tkinter window
root = Tk()
root.title('DaysLeft')
#getting all the windows with their hwnd values
hwnd=gw.getAllWindows()
print(hwnd)
win32gui.SetForegroundWindow(hwnd)
bbox = win32gui.GetWindowRect(hwnd)
img = ImageGrab.grab(bbox)
img.show()
mainloop()
The above code gives error below as expected:.
line 26, in <module>
win32gui.SetForegroundWindow(hwnd)
TypeError: The object is not a PyHANDLE object
You can use PIL for taking a screenshot and win32gui or pygetwindow to get windows location.
Install PIL by saying
pip install Pillow
then your working code would be:
from tkinter import *
from win32gui import FindWindow, GetWindowRect
import pygetwindow as gw
from PIL import ImageGrab
def ss():
win = gw.getWindowsWithTitle('DaysLeft')[0]
winleft = win.left+9
wintop = win.top+38 #change 38 to 7 to not capture the titlebar
winright = win.right-9
winbottom = win.bottom-9
final_rect = (winleft,wintop,winright,winbottom)
img = ImageGrab.grab(final_rect)
img.save('Required Image.png')
#making the tkinter window
root = Tk()
root.title('DaysLeft')
root.after(3000,ss)
root.mainloop()
Why am i subtracting some amount from the pixels? its because, windows has decorations like drop shadow effect to the windows, which are also part of the windows and will be included in the screenshot, so i used this to get rid of those extra pixels.
Or if your still reluctant on using win32gui then, change the function to:
from win32gui import FindWindow, GetWindowRect
from PIL import ImageGrab
......
def ss():
win = FindWindow(None, 'DaysLeft')
rect = GetWindowRect(win)
list_rect = list(rect)
list_frame = [-9, -38, 9, 9] #change -38 to -7 to not capture the titlebar
final_rect = tuple((map(lambda x,y:x-y,list_rect,list_frame))) #subtracting two lists
img = ImageGrab.grab(bbox=final_rect)
img.save('Image.png')
What is after method? It just calls the function after 3000 ms, i.e, 3 seconds. We are basically giving the system some time to build the GUI and capture screenshot.
Hope it helped, do let me know if any errors or doubts.
Cheers

Importing a bit-map image into python says image cannot be opened?

Here is my code:
import random, pygame, sys, math
from pygame.locals import *
def main():
global surface
pygame.init()
surface = pygame.display.set_mode((1153, 649))
pygame.display.set_caption("Dunkin' Density")
start_background = pygame.image.load('Balance_to_begin.bmp')
too_much_left = pygame.image.load('Balance_too_much_left.bmp')
total_balance = pygame.image.load('Total_Balance.bmp')
while True:
surface.blit(start_background, (0,0))
pygame.display.update()
when trying to run it says the image cannot be loaded ...
They are all within the same file, but it isn't working? :(
Make sure the .bmp files and your python script exists in the same directory.

Way to play video files in Tkinter?

Is there a way to play video files like AVI, MP4, etc.?
I tried using PyMedia, but apparently it only works with Pygame.
What is the solution to my problem?
You could use python-gstreamer for playing videos (this works for me on Linux, but it should also work on Windows). This requires python-gstreamer and python-gobject, I would recommend you to use this all-in-one installer.
Here is the code:
import os
import sys
import Tkinter as tkinter
import gobject
import gst
def on_sync_message(bus, message, window_id):
if not message.structure is None:
if message.structure.get_name() == 'prepare-xwindow-id':
image_sink = message.src
image_sink.set_property('force-aspect-ratio', True)
image_sink.set_xwindow_id(window_id)
gobject.threads_init()
window = tkinter.Tk()
window.geometry('500x400')
video = tkinter.Frame(window, bg='#000000')
video.pack(side=tkinter.BOTTOM,anchor=tkinter.S,expand=tkinter.YES,fill=tkinter.BOTH)
window_id = video.winfo_id()
player = gst.element_factory_make('playbin2', 'player')
player.set_property('video-sink', None)
player.set_property('uri', 'file://%s' % (os.path.abspath(sys.argv[1])))
player.set_state(gst.STATE_PLAYING)
bus = player.get_bus()
bus.add_signal_watch()
bus.enable_sync_message_emission()
bus.connect('sync-message::element', on_sync_message, window_id)
window.mainloop()
The following code works for me with GStreamer 1.0 and Python 3 under Ubuntu 16.04. It also enables eight video players stacked in a column in a single window. (The sound channels are simply mixed together.)
The libav/ffmpeg fork created problems under Ubuntu 14.04, which seem to be solved under 16.04. Note that you need the package gstreamer1.0-libav in addition to gstreamer1.0-plugins-*.
The code builds on the 2011 answer by #koehlma, which assumed GStreamer 0.10 and Python 2.
import sys
import os
if sys.version_info[0] < 3:
import Tkinter as tkinter
else:
import tkinter
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GObject
# Needed for set_window_handle():
gi.require_version('GstVideo', '1.0')
from gi.repository import GstVideo
def set_frame_handle(bus, message, frame_id):
if not message.get_structure() is None:
if message.get_structure().get_name() == 'prepare-window-handle':
display_frame = message.src
display_frame.set_property('force-aspect-ratio', True)
display_frame.set_window_handle(frame_id)
NUMBER_OF_FRAMES = 8 # with more frames than arguments, videos are repeated
relative_height = 1 / float(NUMBER_OF_FRAMES)
# Only argument number checked, not validity.
number_of_file_names_given = len(sys.argv) - 1
if number_of_file_names_given < 1:
print('Give at least one video file name.')
sys.exit()
if number_of_file_names_given < NUMBER_OF_FRAMES:
print('Up to', NUMBER_OF_FRAMES, 'video file names can be given.')
file_names = list()
for index in range(number_of_file_names_given):
file_names.append(sys.argv[index + 1])
window = tkinter.Tk()
window.title("Multiple videos in a column using Tk and GST 1.0")
window.geometry('480x960')
Gst.init(None)
GObject.threads_init()
for number in range(NUMBER_OF_FRAMES):
display_frame = tkinter.Frame(window, bg='')
relative_y = number * relative_height
display_frame.place(relx = 0, rely = relative_y,
anchor = tkinter.NW, relwidth = 1, relheight = relative_height)
frame_id = display_frame.winfo_id()
player = Gst.ElementFactory.make('playbin', None)
fullname = os.path.abspath(file_names[number % len(file_names)])
player.set_property('uri', 'file://%s' % fullname)
player.set_state(Gst.State.PLAYING)
bus = player.get_bus()
bus.enable_sync_message_emission()
bus.connect('sync-message::element', set_frame_handle, frame_id)
window.mainloop()
Make use of tkvideoplayer version>=2.0.0 library, which can help you to play, pause, seek, get metadata of the video etc.
pip install tkvideoplayer
Sample example:
import tkinter as tk
from tkVideoPlayer import TkinterVideo
root = tk.Tk()
videoplayer = TkinterVideo(master=root, scaled=True)
videoplayer.load(r"samplevideo.mp4")
videoplayer.pack(expand=True, fill="both")
videoplayer.play() # play the video
root.mainloop()
An example to create a complete video player is in the GitHub page
Refer documentation
Tha easy way is by using tkVideo
to install it
pip install tkVideo
this is script that show you how does it work easily!
from tkinter import *
from tkvideo import tkvideo
root = Tk()
my_label = Label(root)
my_label.pack()
player = tkvideo("C:\\path\\to\\video.mp4", my_label, loop = 1, size = (1280,720))
player.play()
root.mainloop()
this is PyPI link to it for more informations.
koehlma's answer is quite outdated. The "Tkinter" should be "tkinter"; "gst" should "Gst"; "playbin2" should be "playbin". "STATE_PLAYING" should be "State.PLAYING". The below setup and codes works on Debian 11 as of Apr 5, 2022.
First of all, the packages you need to install are
apt install python3-gi python3-gst-1.0 python3-tk
And the code should be updated to:
import os
import sys
import tkinter as tkinter
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst as gst
from gi.repository import GObject as gobject
def on_sync_message(bus, message, window_id):
return
# message does not have structure field any more.
if not message.structure is None:
if message.structure.get_name() == 'prepare-xwindow-id':
image_sink = message.src
image_sink.set_property('force-aspect-ratio', True)
image_sink.set_xwindow_id(window_id)
gobject.threads_init()
window = tkinter.Tk()
window.geometry('500x400')
video = tkinter.Frame(window, bg='#000000')
video.pack(side=tkinter.BOTTOM,anchor=tkinter.S,expand=tkinter.YES,fill=tkinter.BOTH)
window_id = video.winfo_id()
gst.init(None)
player = gst.ElementFactory.make('playbin', 'player')
player.set_property('video-sink', None)
player.set_property('uri', 'file://%s' % (os.path.abspath(sys.argv[1])))
player.set_state(gst.State.PLAYING)
bus = player.get_bus()
bus.add_signal_watch()
bus.enable_sync_message_emission()
bus.connect('sync-message::element', on_sync_message, window_id)
window.mainloop()
I've recently made a package to do this, borderless video player. It also plays audio in sync.
pip install bvPlayer
The code:
from bvPlayer import bvPlayer
bvPlayer("file.mp4")
The repository

Categories

Resources