Python 在另一个循环运行时更新tkinter标签

Python 在另一个循环运行时更新tkinter标签,python,tkinter,Python,Tkinter,您好,我有此代码,我如何在while循环运行时继续升级tkinter标签,即我希望状态保持每秒更改一次以更新状态,而不管我在while循环中的何处 tkinter上的预期输出是正在收集。\n{len(引号)}然后正在收集。。{len(引号)}。。。在while循环完成之前,只需self.destroy() 这段代码对我来说很有用(虽然需要花费一些时间,但我在代码中添加了注释): res=sess.get(next_page),这是什么?应该是res=res.get(next_page)?@jiz

您好,我有此代码,我如何在
while
循环运行时继续升级tkinter标签,即我希望状态保持每秒更改一次以更新状态,而不管我在
while
循环中的何处


tkinter上的预期输出是
正在收集。\n{len(引号)}
然后
正在收集。。{len(引号)}
。。。在
while
循环完成之前,只需
self.destroy()

这段代码对我来说很有用(虽然需要花费一些时间,但我在代码中添加了注释):


res=sess.get(next_page)
,这是什么?应该是
res=res.get(next_page)
?@jizhaosama是的,我修复了它,我的主代码中有sesion,但是构建它的代码太长了,无法准确包含我所寻找的内容,你能解释为什么这样做吗。我不知道为什么只有一个线程可以工作:)@User1984,因为你应该知道
Tk().mainloop()
就像一个while循环。只有当它
break
(可能
destroy()
)时,下一个代码才会运行。与代码中的while循环相同。你使用
while
循环发送
get
请求。只有当它中断时,它会做另一个工作。但是我的线程是一个
非阻塞的
线程。它不会阻塞你的代码。这是一个实现并行性的措施。你也可以阅读关于线程的官方文件。通过这种方式,
中的任何函数都会并行运行,对吗?@User1984是的,但是您应该使用
非块
线程并首先启动它
import tkinter as tk
from tkinter import messagebox
import re,sys
from urllib.parse import urlparse
import requests,time
from bs4 import BeautifulSoup
class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Quotes Scraper v1")
        self.geometry("400x250")
        button = tk.Button(self, text="Collect Links",bd=3, 
            activebackground="grey90",command=self.start_collecting)
        button.place(x=130,y=120)

    def start_collecting(self):
        url = "http://quotes.toscrape.com/"
        res=requests.get(url)
        is res.status_code!=200:
            sys.exit('Check Internet')
        self.clean_screen_plus()
        quotes = []
        while True:
            soup = BeautifulSoup(res.text,'lxml')
            self.update_status()
            quotes+=[i.span.text.strip() for i in soup.findAll('div',{'class':'quote'})]
            try:
                next_page = 'http://quotes.toscrape.com/'+ soup.find('li',{'class':'next'}).a['href']
                time.sleep(5)
                res = requests.get(next_page)
            except AttributeError:
                break
        self.destroy()

    def clean_screen_plus(self,):
        for widget in self.winfo_children():
            widget.destroy()
        self.geometry("300x100")
        self.resizable(False, False)
        self.status = tk.Label(self, text="Collecting")
        self.status.grid()
        self.update_idletasks()

    def update_status(self):

        current_status = self.status["text"]
        if current_status.endswith("..."): 
            current_status = "Collecting"

        else: 
            current_status += "."

        # Update the message
        self.status["text"] = current_status
        self.update_idletasks()
        self.after(1000, update_status) #updates every 1 sec
        print(current_status)
App().mainloop()
import tkinter as tk
from tkinter import messagebox
import re,sys
from urllib.parse import urlparse
import requests,time
from bs4 import BeautifulSoup
import threading

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Quotes Scraper v1")
        self.geometry("400x250")
        button = tk.Button(self, text="Collect Links",bd=3,
            activebackground="grey90",command=self.start_thread) # start a thread instead of starting scrap the page.
        button.place(x=130,y=120)

    def start_thread(self):
        threading.Thread(target=self.start_collecting).start() # create a thread to scrap a page in the background

    def start_collecting(self): # this is your work.
        url = "http://quotes.toscrape.com/"
        res = requests.get(url)
        if res.status_code != 200:
            sys.exit('Check Internet')

        self.clean_screen_plus()
        quotes = []
        while True:
            soup = BeautifulSoup(res.text, 'lxml')
            self.update_status()
            quotes += [i.span.text.strip() for i in soup.findAll('div', {'class': 'quote'})]
            try:
                next_page = 'http://quotes.toscrape.com/' + soup.find('li', {'class': 'next'}).a['href']
                time.sleep(5)
                res = requests.get(next_page)
            except AttributeError:
                break
        self.destroy()

    def clean_screen_plus(self):
        for widget in self.winfo_children():
            widget.destroy()
        self.geometry("300x100")
        self.resizable(False, False)
        self.status = tk.Label(self, text="Collecting")
        self.status.grid()

    def update_status(self):

        current_status = self.status["text"]
        if current_status.endswith("..."):
            current_status = "Collecting"

        else:
            current_status += "."

        # Update the message
        self.status["text"] = current_status
        self.update_idletasks()
        self.after(1000, self.update_status) #updates every 1 sec
        print(current_status)
App().mainloop()