Alright, so my plan is to make a program that will recognize keywords in a tweet and display the tweet in tkinter. Essentially, every time the tweet gets recognized I want it to update a label in tkinter.
I do know how to implement a stream to do this using Twython, but my problem is that I can't have the stream and tkinter running at the same time. I thought about threading, and I tried to, but I have no experience with threading and probably did it wrong.
This is just a stepping stone type project for me in making something more complex, but that is most likely irrelevant. Could somebody maybe point me in the right direction? Heres my code:
from tkinter import *
from threading import Thread
from twython import Twython
from twython import TwythonStreamer
import time
APP_KEY = 'X'
APP_SECRET = 'X'
OAUTH_TOKEN = 'X'
OAUTH_TOKEN_SECRET = 'X'
TRACKING_TERM = 'something'
tweet_text = StringVar
WINDOW_SIZE_X = 1600
WINDOW_SIZE_Y = 300
WINDOW_SIZE_STRING = str(WINDOW_SIZE_X) + 'x' + str(WINDOW_SIZE_Y)
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
t = Thread(target=self.start_stream())
t.start()
self.init_window()
def init_window(self):
self.master.title('Twitter Streamer')
self.pack(fill=BOTH, expand=True)
self.label = Label(self, textvariable=tweet_text)
self.label.place(x=0, y=0)
def start_stream(self):
stream.statuses.filter(track=TRACKING_TERM)
# JWStreamer class is created to handle the streaming
class JWStreamer(TwythonStreamer):
def on_success(self, data):
if 'text' in data:
tweet_text = data['text'].encode('utf-8')
def on_error(self, status_code, data):
print('Error:', status_code)
# To disconnect on error uncomment the next line
# self.disconnect()
print('Waiting 60 seconds to reconnect...')
time.sleep(60)
# Twitter Object
twitter = Twython(APP_KEY,
APP_SECRET,
OAUTH_TOKEN,
OAUTH_TOKEN_SECRET)
# Steamer Object
stream = JWStreamer(APP_KEY,
APP_SECRET,
OAUTH_TOKEN,
OAUTH_TOKEN_SECRET)
root = Tk()
root.geometry(WINDOW_SIZE_STRING)
app = Window(root)
root.mainloop()
I apologize if my code seems kind of sloppy right now. What you are seeing right now is the result of frustratingly moving things around just to make something work.
This might be a little bit of a low quality work around, but I'm quite sure it's generally accepted. Use the after()
method on root
.
I haven't used it, but I understand it allows you to call a function after a period of time. Here's a link to the docs and some questions.
You would have to look up in it, because like I said, I haven't use it before but think it could be helpful to you.