仅限 Windows(据我所知):
好吧,我找到了一种取自Get HWND of each Window?(问题本身)的方法(部分(部分是指函数的大部分)):
import tkinter as tk
def win_focus_set(win_name):
import ctypes
enum_windows = ctypes.windll.user32.EnumWindows
enum_windows_proc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
get_window_text = ctypes.windll.user32.GetWindowTextW
get_window_text_length = ctypes.windll.user32.GetWindowTextLengthW
is_window_visible = ctypes.windll.user32.IsWindowVisible
windows = []
def foreach_window(hwnd, _):
if is_window_visible(hwnd):
length = get_window_text_length(hwnd)
buff = ctypes.create_unicode_buffer(length + 1)
get_window_text(hwnd, buff, length + 1)
windows.append((hwnd, buff.value))
return True
enum_windows(enum_windows_proc(foreach_window), 0)
for hwnd, name in windows:
if win_name in name:
ctypes.windll.user32.BringWindowToTop(hwnd)
def gui_task():
print("doing tasks here")
root.after(50, gui_task)
# main GUI
root = tk.Tk()
root.geometry('%dx%d' % (800, 800))
root.after(50, gui_task)
root.after(1, win_focus_set, 'cmd.exe')
root.mainloop()
基本上它就是那个函数,然后尽快使用.after 调用它,这样它就会在主窗口出现后立即执行(同样"cmd.exe" 只需要在窗口的标题中(所以如果您打开了两个 cmd,它可能会切换到另一个(尽管如果它们都具有相同的标题,即使您提供了完整的标题也可能发生这种情况)并且 .after 将其余参数作为参数传递给预定函数)
另一种选择是获取当前焦点所在的窗口,并在tkinter 启动后将其置于顶部:
import tkinter as tk
import ctypes
hwnd = ctypes.windll.user32.GetForegroundWindow()
def gui_task():
print("doing tasks here")
root.after(50, gui_task)
# main GUI
root = tk.Tk()
root.geometry('%dx%d' % (800, 800))
root.after(50, gui_task)
root.after(1, ctypes.windll.user32.BringWindowToTop, hwnd)
root.mainloop()