在python中用不同的按键调用不同的python函数(Calling different python functions with different key press in python)

系统教程 行业动态 更新时间:2024-06-14 16:58:30
在python中用不同的按键调用不同的python函数(Calling different python functions with different key press in python)

我有两个功能: screenshot()和reader() 。 我想在按下0时调用screenshot() ,按下1时调用reader() 。 如果按下d ,它应该退出。 这是我的尝试:

from PIL import Image import pyscreenshot as ImageGrab import datetime import time import os import pyperclip def screenshot(): if __name__ == "__main__": im=ImageGrab.grab() timestr = time.strftime("%Y%m%d-%H%M%S") file_name = "sample_" + timestr + ".png" file_location = os.path.join('/path', file_name) im.save(file_location) def reader(): pyperclip.copy("sample") while True: x = raw_input('Press enter for a random letter...') print x if x == "0": screenshot() if x == "1": reader() if x == "d": break

但它没有按预期工作。 当我按0 ,没有任何反应。 当我按1 ,没有任何反应。 但是当第一次按d时,它会调用screenshot() 。 下一次d被按下时,它退出。

I have two functions: screenshot() and reader(). I want screenshot() to be called when 0 is pressed, and reader() to be called when 1 is pressed. And it should exit, if d is pressed. This is how I tried:

from PIL import Image import pyscreenshot as ImageGrab import datetime import time import os import pyperclip def screenshot(): if __name__ == "__main__": im=ImageGrab.grab() timestr = time.strftime("%Y%m%d-%H%M%S") file_name = "sample_" + timestr + ".png" file_location = os.path.join('/path', file_name) im.save(file_location) def reader(): pyperclip.copy("sample") while True: x = raw_input('Press enter for a random letter...') print x if x == "0": screenshot() if x == "1": reader() if x == "d": break

But it is not working as expected. When I press 0, nothing happens. When I press 1, nothing happens. But when d is pressed for the first time, it calls screenshot(). And next time d is pressed, it exits.

最满意答案

if __name__ == "__main__":删除此行if __name__ == "__main__": 。 阅读器()正在工作,你知道它是如何工作的吗? 它复制一个sample文本,尝试粘贴到您的文本编辑器。

Remove this line if __name__ == "__main__":. And reader() is working, do you know how it works? its copying a sample text, try to paste in your text editor.

更多推荐

本文发布于:2023-04-15 03:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/895179d457b5a9eb9bcdb792299ee370.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中用   按键   函数   python   press

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!