0

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).

PebNischl
  • 163
  • 5
  • Try adding `root.focus()` after `os.startfile`. If that doesn't work, try `root.focus_force()` instead. – Henry Sep 19 '21 at 22:07
  • @Henry Doesn't work unfortunately. First issue is that opening the file takes some time, so executing `root.focus()` or `root.focus_force()` immediately after `os.startfile` doesn't work, as the focus is still on the tkinter window. I also tried it with a `sleep(3)` before the focus-command, and that doesn't work either: The tkinter window isn't made active, however it does seem to get "refreshed" in a way - on the windows taskbar, the icon for the tkinter window lights up orange, just like when an application gets opened or refreshed in the background. But that's not what I'm after. – PebNischl Sep 20 '21 at 07:51

0 Answers0