如何在 python 中构建计数器? [英] How can I build a counter in python?

查看:37
本文介绍了如何在 python 中构建计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有它,每次我按空格键时,终端中的数字都会增加一,这样我就可以将一个数字记在脑海中并且不会忘记它.但是,如果我为此使用 raw_input,则每次都必须按 Enter 键,这很烦人.我怎样才能建立一个计数器,每次按下空格键时都会增加一个变量?

I want to have it so that each time I hit the space bar, the number in the terminal increases by one, so that I can keep a number in my head and not forget it. However, if I use raw_input for this, I have to hit enter each time, which is annoying. How can I make it so that I build a counter that increases a variable by one each time the space bar is pressed?

这是我所拥有的.

x=0

while x<10000000:
    press = raw_input()
    if  press == "z":
        x=x+1
        print x

推荐答案

如果您使用的是 Linux/Unix,则有 诅咒 模块.

If you are using Linux/Unix, there is the curses module.

import curses

def check_press(scr):
    c = None
    x = 0
    while c != 120: # exit on x
        c = scr.getch()
        if c == 122: # count on 'z'
            x += 1
            scr.addstr(0, 0, "%5d" % x)
            scr.refresh()

if __name__ == '__main__':
    curses.wrapper(check_press)

这篇关于如何在 python 中构建计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆