用键盘inpu制作基本python计数器

2024-05-14 12:35:55 发布

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

这可能听起来很愚蠢,但我似乎不能做一个基本的计数器。基本上,我需要它有两个实时输入,键盘'f'代表正点,键盘'j'代表负点,然后我需要再输入一个'q'来停止迭代,然后打印出f和j键分别按下了多少次。在

编辑:好吧,这很令人沮丧。我搜索了更多,发现实时输入需要msvcrt模块,我使用Windows所以没问题。但是,它仍然什么也不做,代码只是运行并退出,什么都没有发生。在

我想做的是: 1运行代码。 2在背景中打开一个自由式视频。 三。实时按键盘上的j键和f键分别计算自由泳成绩,根据点击次数、正分(j)和负分(f)计算。 4视频结束后,我按q键打印我按j和f键的次数。在

import msvcrt    
def counter():
        negative = 0
        positive = 0
        while True:
            score = input("input starts:")
            if msvcrt.getch() == "f":
                negative += 1
                print(negative)
            if msvcrt.getch() == "j":
                positive +=1
                print(positive)
            if msvcrt.getch() == "q":
                print ("positive", positive)
                print ("negative", negative)
                break

Tags: 代码input视频if计数器代表键盘次数
3条回答

您必须在while循环之外定义positive和{},以保持在每次迭代期间对这些变量所做的更改。E、 g.如是:

def counter():
    score = input("input here:")
    end=1
    positive = 0
    ...

positive==positive+1中有一个小错误。我想你是说positive=positive+1(比较与分配)

计数器的一般语法是正确的,但是如果您想让一些东西在后台运行并且在控制台之外运行,那么您需要一些类似pyHook的东西。getch()在这种情况下不起作用。在

from pyHook import HookManager
from win32gui import PumpMessages, PostQuitMessage

class Keystroke_Watcher(object):
    def __init__(self):
        self.hm = HookManager()
        self.hm.KeyDown = self.on_keyboard_event
        self.hm.HookKeyboard()


    def on_keyboard_event(self, event):
        try:
            if event.KeyID  == keycode_youre_looking_for:
                self.your_method()
        finally:
            return True

    def your_method(self):
        pass

    def shutdown(self):
        PostQuitMessage(0)
        self.hm.UnhookKeyboard()


watcher = Keystroke_Watcher()
PumpMessages()

它将检测按键,然后您可以增加值。当然,您需要推断代码,但是框架已经为您成功做好了准备。在

有很多问题,但这里有一些建议。在

使用num+=1代替num=num+1

在递增计数器之前定义计数器。在

将您的输入移到循环中,否则它将反复使用第一个输入,并且只使用一个输入运行整个循环。在

def counter():
        end=1
        negative = 0
        positive = 0
        while end <= 1000:
            end += 1
            score = input("input here:")
            if score == "f":
                negative += 1
                print(negative)
            if score == "j":
                positive +=1
                print(positive)
            if score == "q":
                print ("positive", positive)
                print ("negative", negative)
                break

    counter()

相关问题 更多 >

    热门问题