简体   繁体   English

暂停(不停止)python 中的 for 循环

[英]pause(not stop) a for loop in python

I have a for loop that read the contents from a file line by line, I need to pause the loop and if button clicked resuming the loop from where it paused.我有一个 for 循环,它逐行从文件中读取内容,我需要暂停循环,如果单击按钮,则从暂停的地方恢复循环。 I searched the internet but I just find a stop button functionality using break for example but I don't want to break from for loop I want to pause/resuming the loop.我搜索了互联网,但我只是找到了一个使用 break 的停止按钮功能,但我不想从 for 循环中中断我想暂停/恢复循环。 thank you in advance for your help here my loop with stop and break, I need to add pause button functionality to it.提前感谢您在这里的帮助,我的循环停止和中断,我需要为其添加暂停按钮功能。

running[0] = True

def csv_exe():
    with open(file_path.get(), 'r') as file:
        data = csv.reader(file, delimiter=',')
        
        for line in data:
            lines= line
            if running[0]== False:
                    break
            else:
                
                    sendmMsg.set(lines)
                    print(lines)
                    time.sleep(0.5)

You can use "yield".您可以使用“产量”。 The pseudo code would be like below.伪代码如下所示。

def csv_exe():
      with open(file_path.get(), 'r') as file:
           data = csv.reader(file, delimiter=',')
           
           for line in data:
                lines= line
                if running[0]== False:
                     yield
                else:
                     sendmMsg.set(lines)
                     print(lines)
                     time.sleep(0.5)


generator=csv_exe()
while True:
  try:
     # if specific button is pressed:
         next(generator)
  except StopIteration:
     break

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

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