gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:32:11 24 4
gpt4 key购买 nike

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()

你好,我有这段代码,如何在 while 循环运行时继续升级 tkinter 标签,即我希望状态每秒不断变化以更新状态,无论我身在何处在 while 循环中。

tkinter 上的预期输出是 Collecting.\n {len(quotes)} 然后是 Collecting.. {len(quotes)} ... 直到 while 循环结束然后只是 self.destroy()

最佳答案

你应该使用一个线程来抓取页面,否则它会阻止它。

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

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()

关于python - 在另一个循环运行时更新 tkinter 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61030143/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com