简体   繁体   English

停止Tkinter中的tweepy流

[英]Stop tweepy streaming in Tkinter

I am trying to stream tweets with python/tweepy using tkinter GUI. 我正在尝试使用tkinter GUI使用python / tweepy流推文。 Ideally, I would have a "Start" button that would start the stream, and a "Stop" button that would stop the stream. 理想情况下,我将有一个“开始”按钮来启动流,并有一个“停止”按钮来停止流。 The next example (from stackoverflow) shows in a simplified way what I try to achieve: 下一个示例(来自stackoverflow)以简化的方式显示了我尝试实现的目标:

import Tkinter as tk
import threading

class App():
    def __init__(self, master):
        self.isrecording = False
        self.button1 = tk.Button(main, text='start')
        self.button2 = tk.Button(main, text='stop')

        self.button1.bind("<Button-1>", self.startrecording)
        self.button2.bind("<Button-1>", self.stoprecording)
        self.button1.pack()
        self.button2.pack()

    def startrecording(self, event):
        self.isrecording = True
        t = threading.Thread(target=self._record)
        t.start()

    def stoprecording(self, event):
        self.isrecording = False
        print "\nStopped"

    def _record(self):
        while self.isrecording:
            print "Downloading tweets"

main = tk.Tk()
app = App(main)
main.mainloop()

I am trying to apply this to my code, the Start button works properly and does everything that it is supposed to do, but the Stop button does not do anything. 我试图将其应用到我的代码中,“开始”按钮可以正常工作,并且可以完成它应该做的所有事情,但是“停止”按钮却什么也没做。 The window does not freeze or anything, its just that the stop button has no effect. 窗口没有冻结或任何停止,只是停止按钮无效。 The stream continues as nothing had happened. 由于没有任何反应,流继续进行。 Here I post my code: 我在这里发布我的代码:

from Tkinter import *
import threading
import codecs
import urllib, json, tweepy,time
from datetime import datetime
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener

consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
keyword = "Poland"

class App():
    def __init__(self, master):
        self.isrecording = False
        self.button1 = Button(main, text='start')
        self.button2 = Button(main, text='stop')
        self.button1.bind("<Button-1>", self.startrecording)
        self.button2.bind("<Button-1>", self.stoprecording)
        self.button1.pack()
        self.button2.pack()

    def startrecording(self,event):
        self.isrecording = True
        t = threading.Thread(target=self._record)
        t.start()

    def stoprecording(self, event):
        self.isrecording = False

    def _record(self):
        while self.isrecording:
            class listener(StreamListener):
                def on_data(self,data):
                    imageFolder = "H:\Bogdan\imageFolder"
                    decoded = json.loads(data)
                    encoded = decoded['text'].encode('ascii','ignore')
                    if "http" not in encoded:
                        encodedStrip = encoded.translate(None, '@,/,\\,",<,>,:,|,?,*').replace("\n","")
                        print encodedStrip
                        if "media" in decoded['entities']:
                            for value in decoded['extended_entities']['media']:
                                imageLink = value['media_url']
                                urllib.urlretrieve(imageLink, imageFolder+"\\"+encodedStrip+"_"+str(time.time())+".jpg")
                        print 'downloading...'
                        return True

                    else:
                        encodedHTTP = encoded[:encoded.index("http")-2]
                        encodedStrip = encodedHTTP.translate(None, '@,/,\\,",<,>,:,|,?,*').replace("\n","")
                        print encodedStrip
                        if "media" in decoded['entities']:
                            for value in decoded['extended_entities']['media']:
                                imageLink = value['media_url']
                                urllib.urlretrieve(imageLink, imageFolder+"\\"+encodedStrip+"_"+str(time.time())+".jpg")
                        print 'downloading...'
                        return True
                def on_error(self,status):
                    print status

            twitterStream = Stream(auth,listener())
            twitterStream.filter( track = [keyword] )



main = Tk()
app = App(main)
main.mainloop()

Any idea on what I have to change to get this working? 对我必须进行哪些更改才能使其正常工作有任何想法吗?

Thank you very much! 非常感谢你!

The problem I guess with your code is that, you initialised a stream object inside the while loop, You must understand that the Stream objects contains an infinite loop within itself, which continuously looks for new streaming tweets. 我猜代码的问题是,您在while循环中初始化了一个流对象,您必须了解Stream对象在其内部包含一个无限循环,该循环不断寻找新的流推文。 So Once you initialise a Stream object, It will automatically run until you kill the process manually, so there is no point in initialising the Stream object under the while loop 因此,一旦初始化Stream对象,它将自动运行,直到您手动终止该进程为止,因此在while循环下初始化Stream对象没有任何意义。

The strategy you need to follow is: 您需要遵循的策略是:

  • Initialise the Stream object when the start button is pressed. 当按下开始按钮时,初始化Stream对象。
  • Stop the streaming when stop button is pressed. 当按下停止按钮时, 停止流式传输。

This behaviour can be easily achieved by editing your on_data() method, you may add the following lines in your on_data() method at the end where return True is being written: 通过编辑on_data()方法可以轻松实现此行为,您可以在on_data()方法的写入return True的末尾添加以下几行:

if isrecording: #Initialise a variable named isrecording.
    return True
else:
    return False

I don't have much knowledge about tkinter but I can tell you the reason your "stop" button isn't working because you're not stopping the stream. 我对tkinter的了解不多,但是我可以告诉您“停止”按钮不起作用的原因,因为您没有停止流。

Within class listener(StreamListener): you need to specify twitterStream.disconnect() . class listener(StreamListener):您需要指定twitterStream.disconnect() What this will do is stop the connection between you and the Streaming API. 这将停止您与Streaming API之间的连接。

This can be added with: 可以添加以下内容:

while isrecording:
    ## enter code here
else:
    ## anything that might apply

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

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