Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何让鼠标和键盘在Pygame中同时工作?_Python_Pygame - Fatal编程技术网

Python 如何让鼠标和键盘在Pygame中同时工作?

Python 如何让鼠标和键盘在Pygame中同时工作?,python,pygame,Python,Pygame,我使用pygame编写了一个简单的代码,用于测试一个玩家同时使用按键和鼠标移动的情况。但是,我无法在按键时移动鼠标。代码如下: import pygame from pygame.locals import * from sys import exit pygame.init() pygame.display.set_mode((640, 480)) while True: for event in pygame.event.get(): if event.type

我使用pygame编写了一个简单的代码,用于测试一个玩家同时使用按键和鼠标移动的情况。但是,我无法在按键时移动鼠标。代码如下:

import pygame
from pygame.locals import *
from sys import exit

pygame.init()

pygame.display.set_mode((640, 480))

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()

    key = pygame.key.get_pressed()
    mouse = pygame.mouse.get_pos()

    pygame.display.update()

多谢各位。尽管问题很简单,但谷歌找不到任何东西。

在for循环池事件中,检测鼠标和按键输入

例如

提供的程序(至少对我来说)能够同时处理鼠标移动和检测按键

简单添加日志信息即可确认这一点:

import pygame
from pygame.locals import *
from sys import exit

pygame.init()

pygame.display.set_mode((640, 480))

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()

    keys  = pygame.key.get_pressed()
    mouse = pygame.mouse.get_pos()

    if ( keys[pygame.K_UP] ):
        print( "up, mouse@ "+str( mouse ), end="     \r" )
    else:
        print( "not up, mouse@ "+str( mouse ), end="     \r" )

    pygame.display.update()
运行此脚本,移动鼠标,定期按↑.

我可以很容易地在输出
向上
不向上
之间切换,鼠标不断移动


如果您不是这样,那么可能是Pygame和您的操作环境出现了一些问题。在这种情况下,我将重新安装PyGame,以确保Python和PyGame的现代版本。

您会说“但是,我无法在按键时移动鼠标”。您是说当您按下某个键时,鼠标不会在屏幕上移动(听起来像是这样,但似乎不太可能),还是说当您检查某个键是否按下时,无法检测鼠标是否移动?是的,当我按住某个键时,鼠标光标会停在屏幕上。我希望鼠标光标能在屏幕上自由移动,这样玩家可以在按住键的同时控制某些东西,但它只是停止了。我还没有看到你描述的行为。我刚刚提出了一个我编写的pygame程序,它使用鼠标和键盘,当按下一个键时,鼠标可以很好地移动。我还复制了上面的代码并运行了它,但也没有看到这种行为。这是在Windows 10上。我注意到,只有在按下以下键之一时,代码才会在我的计算机上工作:箭头键、Shift键、Ctrl键、Alt键、Tab键、Delete键、Insert键和F1到F12键。使用其他键,问题仍然存在,鼠标卡在屏幕上。感谢您的建议。尽管如此,鼠标在按住K_w键或任何其他键时不会在屏幕上移动。您的代码运行良好,我实际上能够在按住K_键的同时在屏幕上移动鼠标,并且打印的消息确认鼠标和K_键同时运行。尽管如此,我还是尝试在代码中将K_改为K_a,在这种情况下,问题仍然存在,鼠标再次停在屏幕上。
import pygame
from pygame.locals import *
from sys import exit

pygame.init()

pygame.display.set_mode((640, 480))

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()

    keys  = pygame.key.get_pressed()
    mouse = pygame.mouse.get_pos()

    if ( keys[pygame.K_UP] ):
        print( "up, mouse@ "+str( mouse ), end="     \r" )
    else:
        print( "not up, mouse@ "+str( mouse ), end="     \r" )

    pygame.display.update()