在不冻结GUI的情况下,在guizero中运行一个函数一段设定的时间



我正在Python中使用guizero(在树莓派上运行(编写一个程序,用户可以选择饮料并使用RFID芯片进行识别。然后,该事务被存储在远程设备上的mariadb中。

这个想法是,用户选择一种饮料,然后屏幕在10秒内变为提示,要求他使用RFID芯片进行身份验证。如果他没有,软件应该返回到主屏幕。

到目前为止,一切都很好,但我在GUI方面遇到了问题。由于10秒扫描周期是一个短暂的循环,它冻结了整个gui,不显示提示,让用户不知道他必须做什么。

我尝试过的:

  • 我使用线程对象来调用扫描函数,但这导致提示消失得很快
  • 我试过回调,但这意味着无论如何都要冻结我的gui
  • 我尝试了应用程序对象的重复方法,并删除while循环,但这意味着系统正在不间断地扫描,这不是故意的

这里有一个小示例代码,它以一种非常简单的方式描述了我的程序:

from guizero import App, Text, PushButton
explanation = "To scan your chip, please click on the button."
def scan():
text.value = "Scanning...."
#set the endtime to ten seconds from now
endtime = time.time() + 10

#repeat for ten seconds
while time.time() < endtime:
print("Scanning for RFID")
print("End of scan")
text.value = explanation


app = App("Funny Title Here")
#initial welcome text
text = Text(app,text=explanation)
#if button is clicked, change the text and scan for ten seconds
button = PushButton(app, command=scan, text="Scan")
app.display()

我知道我尝试的方法之一是正确的,但我似乎缺乏必要的逻辑。所以我的问题是:我该如何实现用户按下按钮后gui更新,开始扫描RFID卡,10秒后停止并返回原始视图?

感谢

我找到了一个解决方案!以下是我解决问题的方法:其想法是,每100毫秒调用一次扫描函数。当用户点击按钮时,布尔值设置为true,扫描函数会执行某些操作。如果布尔值为false,则不会发生任何事情。

import time
from guizero import App, Text, PushButton
explanation = "To scan your chip, please click on the button."
isScan=False
counter = 0
endtime = 0
def scan():
global isScan
if isScan:
global endtime
global counter
#repeat for ten seconds
if time.time()<endtime:
print(f"{counter}")
counter += 1
else:
isScan=False
print("End of scan")
counter = 0 
text.value = explanation


def scanScreen():
global isScan
global endtime
text.value = "Scanning...."
endtime = time.time()+10
isScan = True


app = App("Funny Title Here")
#initial welcome text
text = Text(app,text=explanation)
#if button is clicked, change the text and scan for ten seconds
button = PushButton(app, command=scanScreen, text="Scan")
app.repeat(100,scan)
app.display()

最新更新