Python 2.7 Tkinter GUI Example Code

February 28, 2015
Tags:

Some example code for future reference.


# This accepts preformatted text from textedit and formats it

from bs4 import BeautifulSoup
import collections
import Tkinter as tk
import sys


class MyWindow(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.grid()
        self.article_url = tk.StringVar()
        self.article_title = tk.StringVar()
        self.current_status = tk.StringVar()
        self.choice = tk.IntVar()
        self.article_total = 0
        for items in links.items():
            self.article_total += 1
        self.article_count = 0
        self.label = tk.Label(root, text="Welcome! Where does this article belong?", relief='raised')
        self.label.grid(column=0, row=0, pady=5)

        self.article_title.set(links.items()[0][0])
        self.article_url.set(links.items()[0][1])
        self.article_title_label = tk.Label(root, textvariable=self.article_title, wraplength=500, width=70, height=5, font=('TkDefaultFont', 16), background='lightgrey')
        self.article_title_label.grid(column=0, row=1, padx=0)

        self.article_url_label = tk.Label(root, textvariable=self.article_url, wraplength=550, relief='raised', width=70, height=10)
        self.article_url_label.grid(column=0, row=2)

        #Radio Buttons
        self.radbutton1 = tk.Radiobutton(root, text="Government", variable=self.choice, value=1, background='lightgrey')
        self.radbutton1.grid(column=0, row=3, sticky='w', padx=275)

        self.radbutton2 = tk.Radiobutton(root, text="Private", variable=self.choice, value=2, background='lightgrey')
        self.radbutton2.grid(column=0, row=4, sticky='w', padx=275)

        self.radbutton3 = tk.Radiobutton(root, text="Other", variable=self.choice, value=3, background='lightgrey')
        self.radbutton3.grid(column=0, row=5, sticky='w', padx=275)

        self.radbutton4 = tk.Radiobutton(root, text="Discard", variable=self.choice, value=4, background='lightgrey')
        self.radbutton4.grid(column=0, row=6, sticky='w', padx=275)

        #Submit button
        self.button = tk.Button(root, text="Submit", command=self.looper, background='lightgrey')
        self.button.grid(column=0, row=7)

        #Status label
        self.status_label = tk.Label(root, textvariable=self.current_status, background='lightgrey')
        self.status_label.grid(column=0, row=8)
        self.current_status.set("Start")

        #Zombatar
        self.zombatar_label = tk.Label(image=photo, background='lightgrey')
        self.zombatar_label.grid(column=0, row=8, sticky='w', padx=220)

        #set the default radio button to selected
        self.choice.set(1)

    def looper(self):
        #refresh view to display different article titles and urls

        html_link = '<p><a href="' + links.items()[self.article_count][1] + '" target="blank">' + links.items()[int(self.article_count)][0] + '</a></p>'

        self.article_total -= 1

        if self.article_total < 1:
            self.current_status.set("Done!!!")
            self.button.configure(text='Quit', command=self.quit)

        self.current_status.set(str(self.choice.get()) + ' | ' + str(self.article_count) + ' | ' + str(self.article_total))
        if self.choice.get() == 1:
            #print 'gov ' + html_link
            ordered_dict_final['1'][str(self.article_count)] = html_link

        elif self.choice.get() == 2:
            #print 'priv ' + html_link
            ordered_dict_final['2'][str(self.article_count)] = html_link

        elif self.choice.get() == 3:
            #print 'other ' + html_link
            ordered_dict_final['3'][str(self.article_count)] = html_link

        self.article_count += 1
        try:
            self.article_title.set((links.items()[self.article_count][0]))
            self.article_url.set((links.items()[self.article_count][1]))
        except IndexError:
            self.article_title.set("All Done!")
            self.article_url.set('')

        self.choice.set(1)

    def quit(self):
        #write the output file
        for key in ordered_dict_final.keys():
            if key == '1':
                 outputfile.write(gov_text)
            elif key == '2':
                 outputfile.write(priv_text)
            elif key == '3':
                 outputfile.write(other_text)
            for item in ordered_dict_final[key]:
                 #print ordered_dict_final[key][item].encode('ascii', 'ignore')
                 outputfile.write(ordered_dict_final[key][item].encode('ascii', 'ignore') + '\n')

        outputfile.write('</div>')
        #print 'done!'
        sys.exit()


if __name__ == "__main__":

    root = tk.Tk()
    links = collections.OrderedDict()
    ordered_dict_final = collections.OrderedDict()
    ordered_dict_final['1'] = {}
    ordered_dict_final['2'] = {}
    ordered_dict_final['3'] = {}

    gov_text = '''<!--------------------------------------------------------------------------------------------------------------------------------------------->
<p>&nbsp;</p>
<!--Government News-->
<p>&nbsp;</p>
<!--------------------------------------------------------------------------------------------------------------------------------------------->
<div class="sechead"><img class="article-img" alt="" src="/images/news/article-img/gov.png" />\n'''

    priv_text = '''</div>
<!--------------------------------------------------------------------------------------------------------------------------------------------->
<p>&nbsp;</p>
<!--Private Sector News-->
<p>&nbsp;</p>
<!--------------------------------------------------------------------------------------------------------------------------------------------->
<div class="sechead"><img class="article-img" alt="" src="/images/news/article-img/pri.png" />\n'''

    other_text = '''</div>
<!--------------------------------------------------------------------------------------------------------------------------------------------->
<p>&nbsp;</p>
<!--Other Security News-->
<p>&nbsp;</p>
<!--------------------------------------------------------------------------------------------------------------------------------------------->
<div class="sechead"><img class="article-img" alt="" src="/images/news/article-img/sec.png" />\n'''

    outputfile = open('articles_output.txt', 'w')
    f = open('cyberarticles.html', 'r')
    s = f.read()
    soup = BeautifulSoup(''.join(s))

    for a in soup.find_all('a', href=True):
        links[a.text] = a['href']

    #zombatar ico
    icon = """R0lGODlhIAAgAPeyAL7ZpsfZtczaucnZttbivsbTsc/T0NDS0s3Uz8PSrsvNyNbiwL7PqsjHyMjHx8XIxrvLp8LCwr7Dwby8vLTIore3uK+wr7S0tKysrLi3udLevLW4toyNjZOUk6SkpISEhJaZl0ZKSVlcVUtUQ05cRFFcRUxMTHh2d5ycnK3CnKelqXt7e19iXVRjR2JzVWZyW15tUkRLPKi8lqWop5iXmFVZUmN1T01QUKinqKa2mIWIh05TTVViS6irl52yjJ2nkEdRQ1xrTj5GOX2AfImHiXZ4eFpmUW9zcpqtiGx6XYONdHuHdHR9ZWtzWzs8O5iniC42LEJSOG6BYp6rk4aSenOCZG15YUZMRGZraYeHiJapg3mLaKWojpKTfoaGd2lpV5prapWlgmFkXJOUgqeok7e3nouUfHN0YYqAdMnVtI2he3p5dHyDa2BuUnaDamd6VVNTU4abdXh3eG2BW2Z4WXJzclJbTElWPVlTVGtra1tbW1pkTFdZRGVkT0RINx8nIldZWmRkZH6SbWlnaWZpZlFOTWNbXPHy5lpJQrGon0IsKUZEOF5fYF9jYktKO0ozL0suLUpMRDc2Nzc4MlVCPtfPx0NDQ1pXWcHNrGRuXFJWTFJNQCInIYmRhj9BPEI4O3hUVptAOY9IRmpkZp1ERNsUE79QTddydd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RxaR568LAHH2f0wccdfuzBmQt3GPEHIP54BBKIp3mkIUiHgxBCyCB5mFCIIYeggUgiiixSQmskxLDDCoHo4QQjuRawRSCNyGqtrIY48ggkjyiCiCKN+hGJJLIOYsIkgAQiLSN6tOtuuyKsQQkkkChSySNBvMGDJZdwkG4geIjgBCCYbAHIwQiLcAkgQGSiSSSObOKHI3sYwYmzsVqrBxxOJFAFHDfgAcfII+MRQgxNdJKJC22QIAQHN6Awax6zBgKHJSZAMIcJPBfi688meGLECiYAYfQnK+BxSbV1yKpHIZbcgMkckYRgQghWX421CZZ0XWAHoIQiyiiynpBHI3DwDAcmdHTt9ttuO8H1EB2QUoopp6ACimQdbrAhRiGFSP2GE5444cQnlhhueOJOWOLJCVgQkooqqpwChh2YCWEJyAy44MQqkhguSeijKy6JH4zIQcgorLRCdnAvOHHDDWu7okUYuOeuu+6v5MAFLMD/8MMrSDxhxivIxxIQADs="""
    photo = tk.PhotoImage(format='gif', data=icon)
    root.tk.call('wm', 'iconphoto', root._w, photo)
    root.geometry("650x460+250+250")
    root.configure(background='lightgrey')
    root.resizable(False, False)
    root.title("Article Sorter")
    root.lift()
    MyWindow(root)
    root.mainloop()

Leave a Reply