Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- __author__ = 'Joseph Davies'
- from tkinter import *
- import webbrowser, praw
- news_program = praw.Reddit(user_agent='News Program v2 + GUI by Joseph')
- user_name = 'Redditor' # Put your user name here
- password = 'RedditorPassword' # Put your password here
- class RedditNewsGUIHeader(Frame):
- """
- Generates frame that contains a listbox and entry field.
- Allows users to choose the subreddit and offers basic filtering options
- """
- def __init__(self, master=None):
- Frame.__init__(self, master)
- self.sort_options = ['Top', 'Rising', 'New', 'Hot']
- self.login_status = Label(self, text='{}'.format(self.login()), font=('Times New Roman', 10), bg='light green')
- self.master.title('GUI for Reddit News API designed by /u/TheEnergizerBunny')
- self.pack(anchor=W)
- self.config(bg='light green')
- self.sort = Listbox(self, height=1, selectmode=SINGLE)
- self.sort.grid(row=0, column=0, padx=10, pady=(20,20))
- for option in self.sort_options:
- self.sort.insert(END, option)
- self.sort_scrollbar = Scrollbar(self, orient=HORIZONTAL)
- self.sort_scrollbar.grid(row=0, column=0, sticky='EW', padx=10, pady=(45,10))
- self.sort_scrollbar.configure(command=self.sort.yview)
- self.sort.configure(yscrollcommand=self.sort_scrollbar.set)
- self.subreddit_label = Label(self, text='Subreddit:', bg='light green', padx=8, font=('Times New Roman', 10))
- self.subreddit_label.grid(row=0, column=2)
- self.input_subreddit = Entry(self)
- self.input_subreddit.grid(row=0, padx=(0,5), column=3)
- self.redditor_label = Label(self, text='Redditor:', bg='light green', padx=1, font=('Times New Roman', 10))
- self.subreddit_submit = Button(self, text='Submit', command=lambda: self.getsub())
- self.subreddit_submit.grid(row=0, column=4, padx=(0, 40))
- self.redditor_label.grid(row=0, column=5)
- self.login_status.grid(row=0, pady=10, padx=(0,200), column=6, sticky=E)
- def getsub(self):
- try:
- self.list.destroy()
- except:
- pass
- self.c_sort = list(self.sort.curselection())
- self.c_sort = self.sort_options[self.c_sort[0]]
- self.c_subreddit = self.input_subreddit.get()
- self.list = RedditNewsGUI(self.c_sort, self.c_subreddit)
- def login(self):
- """
- Attempts to log in using the provided username and password.
- """
- try:
- news_program.login(user_name, password)
- except ResourceWarning as rw:
- pass
- except praw.errors.InvalidUserPass as iup:
- return '{} could not be logged in'.format(user_name)
- return '/u/{} is logged in'.format(user_name)
- class RedditNewsGUI(Frame):
- def __init__(self, sort, subreddit, master=None):
- """
- Creates the frame that contains the retrieved post titles and buttons linking to the source url.
- Allows the user to upvote or downvote.
- """
- self.u_buttons = []
- self.d_buttons = []
- self.s_buttons = []
- self.n_labels = []
- self.sort = sort
- self.subreddit = subreddit
- Frame.__init__(self, master)
- self.pack()
- self.news_list = self.get_news()
- self.create_widgets()
- def create_widgets(self):
- """
- Creates empty lists to store widget objects.
- Loops 10 times to create multiple label and button objects.
- Configures the state of the widget object values.
- Structures button and label objects in a grid layout.
- """
- for i in range(len(self.news_list)):
- self.u_buttons.append(Button(self, text='Upvote', width=12, bg='light grey'))
- if self.news_list[i + 1][2].likes is True:
- self.u_buttons[i].config(bg='green')
- self.d_buttons.append(Button(self, text='Downvote', width=12, bg='light grey'))
- if self.news_list[i + 1][2].likes is False:
- self.d_buttons[i].config(bg='red')
- self.s_buttons.append(Button(self, text='{}'.format('S'), width=3, bg='#acff99'))
- self.u_buttons[i]['command'] = lambda i=i: self.upvote(i)
- self.d_buttons[i]['command'] = lambda i=i: self.downvote(i)
- self.s_buttons[i]['command'] = lambda i=i: self.goto_source(i+1)
- self.u_buttons[i].grid(row=i+1, column=0, padx=5, sticky=W)
- self.d_buttons[i].grid(row=i+1, column=1, sticky=W)
- self.s_buttons[i].grid(row=i+1, column=2, padx='3', sticky=W)
- self.n_labels.append(Label(self, text='{}. {}'.format((i+1), self.news_list[i+1][0]), wraplength=550,
- justify=LEFT, font={'font':['courier', 50, 'italic']}).grid(row=i+1, column=3,
- padx=5, sticky=W))
- def get_news(self):
- """
- Reterives the top 10 trending news from /r/news using PRAW
- Returns the titles and url of each story stored in a dictionary
- """
- news_dict = {}
- if self.sort == 'Hot':
- self.submissions = news_program.get_subreddit(self.subreddit).get_hot(limit=10)
- elif self.sort == 'Top':
- self.submissions = news_program.get_subreddit(self.subreddit).get_top(limit=10)
- elif self.sort == 'Rising':
- self.submissions = news_program.get_subreddit(self.subreddit).get_rising(limit=10)
- else:
- self.submissions = news_program.get_subreddit(self.subreddit).get_new(limit=10)
- count = 1
- for submission in self.submissions:
- news_dict[count] = [submission.title, submission.url, submission, submission.likes]
- count += 1
- return news_dict
- def downvote(self, num):
- """
- Downvote the post
- """
- if self.d_buttons[num]['text'] == 'Downvote':
- self.news_list[num + 1][2].downvote()
- self.d_buttons[num].config(text='Gromit', bg='red')
- self.u_buttons[num].config(text='Upvote', bg='light grey')
- else:
- self.d_buttons[num].config(text='Downvote', bg='light grey')
- self.news_list[num + 1][2].clearvote()
- def upvote(self, num):
- """
- Upvote the post
- """
- if self.u_buttons[num]['text'] == 'Upvote':
- self.news_list[num + 1][2].upvote()
- self.u_buttons[num].config(text='Wallace', bg='dark green')
- self.d_buttons[num].config(text='Downvote', bg='light grey')
- else:
- self.u_buttons[num].config(text='Upvote', bg='light grey')
- self.news_list[num + 1][2].clearvote()
- def goto_source(self, num):
- """
- Opens the link in a web browser
- """
- webbrowser.open(self.news_list[num][1], new=1)
- self.s_buttons[(num-1)].config(bg='light grey')
- ################################################################################
- # Main code
- header = RedditNewsGUIHeader()
- header.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement