guizero Raspberry Pi:按钮->命令序列问题

问题描述 投票:0回答:1

[必需:在guizero App上按下按钮应首先设置一个文本值,然后执行一个功能(这里是一个简单的time.sleep();最初是一个子进程);执行该功能后,应显示结果文本;

#!/usr/bin/python3
# -*- coding: utf-8 -*-

from guizero import App, PushButton, Text
import subprocess
import time

# Action you would like to perform
def counter0():
    global s0
    text0.value = int(text0.value) + 1  # works
    text1.value = s0                    # works

def counter1():
    global s0
    text1.value = s0       # display a status value - but does not (!)
    time.sleep(1)          # originally a subprocess is called here; works
    text1.value = "ready"  # only diplays this after a delay

s0="start something after pressing butt1"

app = App("Hello world", layout="grid")

text0 = Text(app, text="1", align="left", grid=[0,1])
text1 = Text(app, text=s0, align="left",grid=[0,8] )
butt1 = PushButton(app, text="Button", command=counter1, align="left", grid=[0,2])
text0.repeat(10000, counter0)  # Schedule call to counter() every 1000ms

app.display()

[很可能我不了解guizero背后的想法。任何想法如何管理此类需求?

python python-3.x tkinter raspberry-pi3 guizero
1个回答
0
投票

如果我正确理解了您的问题,则您的特定问题在这里:

    text1.value = s0       # display a status value - but does not (!)

这不起作用,因为guizero框架正在同步执行该功能:直到该函数返回之前,没有其他代码可以执行-包括更新显示的代码。

如果您想:

  • 使用subprocess运行命令之前显示消息
  • 运行一些命令
  • 在命令完成后显示消息

然后,您将需要重写逻辑,以使您的应用程序不必等待counter1完成。异步运行代码的一种方法是在单独的线程中运行它。例如:

from guizero import App, PushButton, Text
import threading
import time


# Action you would like to perform
def counter0():
    global s0
    text0.value = int(text0.value) + 1  # works
    text1.value = s0                    # works


def run_command():
    time.sleep(1)          # originally a subprocess is called here; works
    text1.value = "ready"  # only diplays this after a delay


def counter1():
    global s0
    text1.value = "Running command..."
    threading.Thread(target=run_command).start()


s0 = "start something after pressing butt1"

app = App("Hello world", layout="grid")

text0 = Text(app, text="1", align="left", grid=[0, 1])
text1 = Text(app, text=s0, align="left", grid=[0, 8])
butt1 = PushButton(app, text="Button", command=counter1,
                   align="left", grid=[0, 2])
text0.repeat(10000, counter0)

app.display()

运行上面的代码将给您以下行为:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.