设置循环以检测按键输入不和谐.py

2024-06-06 22:43:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在我的代码中使用按键检测这些天,似乎很难推动按键检测功能的应用不和谐.pybot循环函数

显然这就是我一直在尝试的

    import pyscreenshot as ps
    import keyboard
    from PIL import Image
    from discord.ext import commands
    client=commands.Bot("!")
    async def keypress_detector():
        while True:
            try:  
                if keyboard.is_pressed('['):#if key '[' is pressed 
                    im=ps.grab()
                    im.save("screenie.png")
                    image_obj = Image.open("screenie.png")
                    cropped_image = image_obj.crop((130, 445, 580, 812))
                    cropped_image.save("updated.png")
                    await client.send_file(client.get_channel('id-here'), "updated.png")
                else:
                    pass
            except Exception as ex:
                return print(str(ex))
    if __name__ == "__main__":
       client.loop.create_task(keypress_detector())   
       client.run("TOKEN")

如果我只想正常运行这个函数(在bot循环之外,虽然它不会将屏幕截图发送到频道),我希望bot在我按下某个键时将屏幕截图发送到聊天室,那么这个函数的工作效果非常好。如果有别的办法,请告诉我。你知道吗

更新

把它修好了,前几次不起作用,但现在起作用了。你知道吗


Tags: 函数fromimageimportclientifpngas
1条回答
网友
1楼 · 发布于 2024-06-06 22:43:13

因为while True导致了一个非异步的无限循环(不和谐.py依赖于此)你会遇到问题。我不确定在python领域或任何语言中,您想要实现的目标是否真的可行。我也不知道你在这里想要达到什么目的,如果你知道我错了,就纠正我。你知道吗

相关问题 更多 >