简体   繁体   English

Python-在脚本后台运行while循环

[英]Python- run a while loop in background of script

So I have this script for controlling an LCD plate where I want the backlight to change every time you press a button, but also want to do other things as well. 因此,我有这个脚本来控制LCD板,我希望在每次按下按钮时都可以改变背光,但是我也想做其他事情。 Currently this doesn't work and it doesn't display the messages I want it to. 目前,这不起作用,并且不会显示我想要的消息。

This is the change backlight bit of code: 这是代码的更改背光位:

while True:
    for b in btn:
        if lcd.buttonPressed(b):
            lcd.backlight(col[randint(0,5)])

And then I want to go on and run a bit of code that prints a string to the lcd and stuff, in this way: 然后,我想继续运行一些代码,以这种方式将字符串打印到液晶显示器和其他东西上:

lcd.message("This is a string")

but the script doesn't ever print the string, it just stays on the backlight change-y bit. 但是脚本永远不会打印字符串,而只是停留在背光的y位置。

Basically I'm creating an index of letters that you can move through using the LCD buttons, and want the backlight to change each time you press a button. 基本上,我正在创建一个字母索引,您可以使用LCD按钮浏览这些字母,并希望每次按按钮时改变背光。

The standard way is to have a single loop containing both. 标准方法是让一个循环包含两个循环。 In the loop you first handles any input or state changes. 在循环中,您首先要处理任何输入或状态更改。 Then at the end of your loop you update display. 然后,在循环结束时更新显示。 This is a fairly common paradigm in game programming see pygame for tons of examples. 这是游戏编程中相当普遍的范例,有关大量示例,请参见pygame You would then only break once your program is terminating. 然后,只有在程序终止后才中断。 One thing worth pointing out is that you would not want to block on checking for key press (or any input), otherwise you would hold up your display waiting for input. 值得指出的一件事是,您不想阻止检查按键(或任何输入),否则您会抬起显示器等待输入。

sudo code would be something like: sudo代码将类似于:

while True:
    for event in key_presses():
        handle_event(event)  # stuff that happens as a result of input
    update_state()  # stuff that happens regardless of input
    update_display()  # everything that changes the display (backlight, text, anything)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM