好吧,所以我的计划是创建一个程序来识别推文中的关键字并在tkinter中显示推文。基本上,每次推文被识别时,我都希望它更新tkinter中的标签。
我知道如何使用Twython实现流来实现这一点,但我的问题是我无法同时运行流和tkinter。我想过线程,我试过,但我没有线程经验,可能做错了。
对于我来说,这只是一个踩踏石头的项目,可以让事情变得更复杂,但这很可能无关紧要。有人可能会指出我正确的方向吗?继承我的代码:
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()
如果我的代码现在看起来很草率,我道歉。你现在所看到的是令人沮丧地移动东西只是为了让事情有效。