python-3.x - while循环在一段时间后不会停止
问题描述
嗨,我在这里有我的代码,它连接在我的 tkinter GUI 中,并且我读到 tkinter 会在其中存在循环时冻结,因为它也是一个循环。所以我在这里要做的是给这个函数一些时间,比如 45 秒,然后在这段时间过去后打破循环。我也尝试过线程,但我知道如何正确实现它,这就是我想出这个解决方案的原因。但是在我尝试了这个之后,循环不会在 45 秒后中断。我究竟做错了什么?这个能用吗?非常感谢您提前。我确实看过很多关于线程和队列的教程,但是对于像我这样的初学者来说非常复杂,所以如果这个可以工作,请帮助我。再一次感谢你!
import serial
port = '/dev/ttyUSB0'
balance = 0
timeout = time.time() + 45
#get Pulse from Arduino
def getPulse():
try:
ser = serial.Serial(port, 9600)
while True:
read = ser.readline()
try:
value = int(read, 10)
if (value != 0):
print(value)
break
except ValueError:
pass
finally:
return value
#Update Balance
def balanceCounter(coins):
total = 0
total += coins
return total
def getCoins():
pulse = getPulse()
coinvalue = 0
if pulse == 1:
coinvalue = 1
print("1 Inserted")
elif pulse == 5:
coinvalue = 5
print("5 Inserted")
elif pulse == 10:
coinvalue = 10
print("10 Inserted")
return coinvalue
def mainCounter(numpages):
global balance
#input target Sample Amount
targetValue = numpages
tbalance = 0
try:
while tbalance <= int(targetValue):
coins = getCoins()
balance = balanceCounter(coins)
tbalance += balance
print("Total balance : "+str(tbalance))
if tbalance >= int(targetValue) or time.time() > timeout:
break
finally:
return tbalance
解决方案
推荐阅读
- python - 月份的正确顺序 Python
- swift - 我的 UIViewController 中出现了额外的空白
- c# - Microsoft.Data.ConnectionUI.DataConnectionDialog
- visual-studio - 无法使用 Web 部署将网站发布到服务器
- javascript - javascript中的for循环数组
- sql-server - SQL:如何在数据库中的所有视图中搜索 ID 并列出提供结果的视图和列名称?
- c++ - 为什么我只为 bool 和 int 而不是 double 获得 -Wunused-lambda-capture?
- python - 带有后续运算符的 Python 加法和减法
- android - 用户滚动时如何从滑动显示 RecyclerView 菜单项中隐藏底部布局?
- struts2 - Struts 2 中 org.apache.struts.taglib.bean.WriteTag 和 org.apache.struts.taglib.logic.PresentTag 等类的替代方案是什么?