我正在尝试使用pygame制作游戏,最后会弹出tkinter消息,显示游戏结束消息,并提供再次播放的选项。当我按下“再次播放”按钮时,按此键时,播放器精灵完全不会移动。然后我发现发生了这种情况,因为在我按下消息框按钮后,它没有将焦点转移到活动的pygame窗口。如果有人告诉我如何更改焦点窗口,这将很有帮助。
谢谢!
答案 0 :(得分:0)
如果您使用 Windows,则可以使用 win32gui
模块,尤其是 SetFocus()
方法。
例如,以下程序受 this 页面的启发,创建了一个 tkinter
窗口和一个 pygame
窗口,并将它们交替显示。
# -------------------------------
# initialise the front() function
import win32gui
def windowEnumerationHandler(hwnd, windows):
windows.append((hwnd, win32gui.GetWindowText(hwnd)))
results = []
windows = []
win32gui.EnumWindows(windowEnumerationHandler, windows)
def front(win_name):
for i in windows:
if i[1] == win_name:
win32gui.ShowWindow(i[0],5)
win32gui.SetForegroundWindow(i[0])
break
# ------------------------
# create the pygame window
import pygame
class PygameWindow:
def __init__(self, name):
self.name = name
self.window = pygame.display.set_mode((640, 480))
pygame.display.set_caption(self.name)
def to_front(self):
front(self.name)
pygame_window = PygameWindow('This is the pygame window')
# -------------------------
# create the tkinter window
import tkinter
class TkinterWindow:
def __init__(self, name):
self.name = name
self.window = tkinter.Tk()
self.window.title(self.name)
def to_front(self):
front(self.name)
tkinter_window = TkinterWindow('This is the tkinter window')
# ------------------------------------------
# main loop - switch between the two windows
from time import sleep
while True:
sleep(1)
pygame_window.to_front()
sleep(1)
tkinter_window.to_front()
# update the tkinter window to make it to stay visible
tkinter_window.window.update()