I have a tkinter application where a few hotkeys are implemented to play various mp3-files. Basically, this:
import tkinter as tk
import os
root=tk.Tk()
def openFile(event=None):
os.startfile("Song.mp3")
openFile()
root.bind("<space>", openFile)
root.mainloop()
This works, but if I press space to play the sound file, the music player now becomes the active window. This means that pressing space again doesn't do anything anymore (or rather, it does whatever the space bar does in the music player). To replay the file, I first need to click back on the tkinter-window to make it active, and only then I can press space again to play the file again (which then again activates the music player window and deactivates the tkinter window). Is there any way for me to open the sound file with the music player but keep the current window as the active one, so that I don't have to manually reactivate it after every play? Note that I don't necessarily want the tkinter window to always be the active window, just when I open a file from it. As an example, if I deliberately click on the music player, then the player window should be made active instead of the tkinter one.
EDIT: Okay, got it working, using win32gui:
import tkinter as tk
import os
import win32gui, win32com.client
def windowEnumerationHandler(hwnd, windows):
windows.append((hwnd, win32gui.GetWindowText(hwnd)))
windows = []
def front(windowID, windows):
for i in windows:
if i[0] == windowID:
shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys('+')
win32gui.SetForegroundWindow(i[0])
break
root=tk.Tk()
def openFile(event=None):
windowID = win32gui.GetForegroundWindow()
win32gui.EnumWindows(windowEnumerationHandler, windows)
os.startfile("Pause.mp3")
front(windowID, windows)
openFile()
root.bind("<space>", openFile)
root.mainloop()
The shell-part seems to be necessary, see for example here. I changed the SendKeys-command from % to +, as I also have a menu bar in my full program, which gets opened via the alt key (which isn't supposed to happen when I play the sound file).