【发布时间】:2020-11-04 23:17:06
【问题描述】:
我编写了一个 GUI 来控制测量设备及其数据采集。
代码的简化草图如下所示:
def start_measurement():
#creates text file (say "test.txt") and write lines with data to it continuously
def stop_measurement():
#stops the acquisition process. The text file is saved.
startButton = Button(root, text = "start", command = start_measurement)
endButton = Button(root, text = "end", command = stop_measurement)
此外,我还有一个实时分析输出文本文件的函数,即它在通过无限while 循环写入文本文件时连续读取文本文件:
def analyze():
file_position = 0
while True:
with open ("test.txt", 'r') as f:
f.seek(file_position)
for line in f:
#readlines an do stuff
fileposition = f.tell()
现在我想在按下 START 按钮时启动分析功能并在按下 END 按钮时结束分析功能,即跳出while 循环。我的想法是放置一个标志,它初始化while 循环,当按下 END 按钮时,标志值会发生变化,你会跳出 while 循环。然后只需将分析功能放在开始测量功能中即可。
有点像这样:
def analyze():
global initialize
initialize = True
file_position = 0
while True:
if initialize:
with open ("test.txt", 'r') as f:
f.seek(file_position)
for line in f:
#readlines an do stuff
fileposition = f.tell()
else: break
def start_measurement():
#creates text file (say "test.txt") and writes lines with data to it
analyze()
def stop_measurement():
#stops the acquisition process
initialize = False
startButton = Button(root, text = "start", command = start_measurement)
endButton = Button(root, text = "end", command = stop_measurement)
所以这是我幼稚的新手想法。但问题是当我点击开始按钮时,结束按钮被禁用,因为我正在进入无限循环,我猜我无法停止这个过程。我知道这有点含糊,但也许有人对如何处理这个问题有想法?我也想过使用线程,但无法使其工作。我不知道这是否是一个好方法。
【问题讨论】:
-
你应该创建一个运行无限循环的线程。
标签: python user-interface tkinter