【问题标题】:Start and stop command to break a loop开始和停止命令以打破循环
【发布时间】:2021-01-07 18:56:28
【问题描述】:

我正在编写网页抓取代码,这个过程很长。因此,我想以一种奇特的方式启动和停止它,使用 tkinter 的按钮。但我在网上找不到任何解决方案。

  • .after() 函数似乎不是一个好的选择,因为我不想每次都重新启动循环。我的循环已经基于从另一个文档中读取并解析每个文档的 url 工作。
  • 我尝试了.join() 的线程选项。但无法解决我的问题。但也许我没有正确编写代码。

我的问题可以表述如下:

开始 → 读取 urls 文档并启动解析循环。

停止 → 停止解析并保存内容。

例如,我希望下面的代码可以工作:

from tkinter import *

flag=False

def test_loop():
    while flag==True:
        print("True")
    while flag==False:
        print("False")

def start():
    global flag
    flag=True
    test_loop()

def stop():
    global flag
    flag=False
    test_loop()

root = Tk()
root.title("Test")
root.geometry("500x500")

app = Frame(root)
app.grid()

start = Button(app, text="Start", command=start)
stop = Button(app, text="Stop", command=stop)

start.grid()
stop.grid()

root.mainloop()

【问题讨论】:

  • 在 tkinter 应用程序中,您可能需要以某种方式使用 after() 以避免导致 GUI“挂起”——您不能干扰其 @987654326 的运行@。使用 join() 并不是一个真正的选择,因为 tkinter 不直接支持多线程。解决此问题的一种方法是使用我对问题Freezing/Hanging tkinter Gui in waiting for the thread to complete 的回答。
  • 谢谢马蒂诺。我去看看。
  • 不幸的是,我无法用你的方法让它工作。这很复杂,所以也许我没有正确修改您的代码以适应我的情况。我会尽量说得更清楚。

标签: python loops tkinter


【解决方案1】:

这样做:

while links and not stopped:
     # scraping here

您可以使用按钮控制stopped bool 标志。

【讨论】:

  • 感谢 AlanWik,我试过了,但它不起作用。当循环工作时,控制停止标志的命令对其没有影响。
【解决方案2】:

您需要导入线程库,因为 python 一次只接受一个命令,因此线程将创建多个线程来同时处理多个任务。 这是更新后的代码:

from tkinter import *
import threading

flag=False

def test_loop():
    while flag==True:
        print("True")
    if flag==False:
        print("False")

def start():
    global flag
    flag=True
    thread.start() #thread start

def stop():
    global flag
    flag=False
    thread.join() #thread stop

#this is the point where you will create a thread
thread=threading.Thread(target=test_loop)

root = Tk()
root.title("Test")
root.geometry("500x500")
app = Frame(root)
app.grid()

start = Button(app, text="Start", command=start)
stop = Button(app, text="Stop", command=stop)
start.grid()
stop.grid()

root.mainloop()

【讨论】:

  • 感谢死亡大师。确实,这与我找到的解决方案完全相同。这个应该也可以。
【解决方案3】:

好的,我确实使用标志系统解决了这个问题。

from tkinter import *
import threading


def st1():
    global go1
    global go2
    go1=True
    while go1==True:
        go2=False
        print('Start')

def st2():
    global go1
    global go2
    go2=True
    while go2==True:
        go1=False
        print('Stop')


def thread1():
    threading.Thread(target=st1).start()

def thread2():
    threading.Thread(target=st2).start()


root = Tk()
root.title("Test")
root.geometry("500x500")

app = Frame(root)
app.grid()

start = Button(app, text="Start", command=thread1)
stop = Button(app, text="Stop", command=thread2)

start.grid()
stop.grid()

root.mainloop()

感谢您的帮助,这很有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-21
    • 2011-09-25
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多