Как остановить oop кнопкой остановки? - PullRequest
0 голосов
/ 02 апреля 2020
    import requests
    from bs4 import BeautifulSoup
    import time
    from tkinter import *
    from tkinter import messagebox

    button = Tk()
    button.geometry("500x300")
    button.title("기사 자동 모니터링") 

    def start():
        global job1
        keyword = "기업"
        url = "https://search.naver.com/search.naver?where=news&query={}&sm=tab_srt&sort=1&photo=0&field=0&reporter_article=&pd=0&ds=&de=&docid=&nso=so%3Add%2Cp%3Aall%2Ca%3Aall&mynews=0&refresh_start=0&related=0".format(keyword)
        r = requests.get(url)
        bs = BeautifulSoup(r.text, "lxml")
        articles = bs.select("ul.type01 > li")

        for ar in articles:
            title1 = ar.select_one("a._sp_each_title").text #기사제목 = title1
            print(title1)

        time.sleep(5)

        keyword = "기업"
        url = "https://search.naver.com/search.naver?where=news&query={}&sm=tab_srt&sort=1&photo=0&field=0&reporter_article=&pd=0&ds=&de=&docid=&nso=so%3Add%2Cp%3Aall%2Ca%3Aall&mynews=0&refresh_start=0&related=0".format(keyword)
        r = requests.get(url)
        bs = BeautifulSoup(r.text, "lxml")
        articles = bs.select("ul.type01 > li")

        for ar in articles:
            title2 = ar.select_one("a._sp_each_title").text #기사제목 = title2
            print(title2)

        if title1 != title2:
            print("기사가 업데이트 되었습니다.")
            messagebox.showinfo("알림","기사가 업데이트 되었습니다.")
            time.sleep(5)

        else:
            time.sleep(5)

    b = Button(button,text="모니터링 시작",command=start,width=30,height=5,activebackground="orange").place(x=143, y=50) #버튼 설정

    stopButton = Button(button,text="종료", command=button.destroy, width=30,height=5,).place(x=143, y=150)

    button.mainloop()

1 Ответ

0 голосов
/ 02 апреля 2020

Вы должны создать переменную-флаг, например:

class Loop:
    def __init__(self, tk):
        self.running = True
        self.tk = tk
        Button(tk, command=self.stop, text='Stop the loop').pack()
    def stop(self):
        self.running = False
    def loop(self):
        while self.running:
            #do_stuff()
            self.tk.update()
tk = Tk()
#init()
Loop().loop()

Изучите программирование на основе событий. Надеюсь, что это полезно!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...