0

Hello I created this function that allows you to count the top X words in the Macbeth play however I want to display the results in a gui of my creation and was wondering if someone could show me how to? I already created the function and tested it but I don't understand python gui and whenever I try to create it, I run into a host of errors.

#Imports
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from collections import Counter
import collections

# Initialize the dictionary
wordcount = {}

#Function
#open Macbeth text file
file = open('Macbeth Entire Play.txt', encoding="utf8")
a= file.read()

n_print = int(input("How many most common words are: "))
print("\nThe {} most common words are as follows\n".format(n_print))
word_counter = collections.Counter(wordcount)
for word, count in word_counter.most_common(n_print):
    print(word, ": ", count)
# Close the file
file.close()

#Graphics
fullString = ""
root = tk.Tk()
root.title("Count words")
root.geometry('400x400')

#Background Image Label
bg = PhotoImage(file = "./guibackground.gif")

# Show image using label 
label1 = Label( root, image = bg) 
label1.place(relx=0.5, rely=0.5, anchor=CENTER) 

#Class Window
class Window:

     def __init__(self):

        self.root = tk.Tk()
        self.btn = tk.Button(text='Open File', command=self.open_file)
        self.btn.pack()
        self.btn = tk.Button(text='Exit', command=root.quit)
        self.btn.pack()
        self.lbl.pack()
        self.root.mainloop()

     def open_file(self):
    
       file = open('Macbeth Entire Play.txt', encoding="utf8")
a= file.read()

def word_count(self):
        for word in a.lower().split():
             word = word.replace(".","")
             word = word.replace(",","")
             word = word.replace(":","")
             word = word.replace("\"","")
             word = word.replace("!","")
             word = word.replace("“","")
             word = word.replace("‘","")
             word = word.replace("*","")
             if word not in wordcount:
                  wordcount[word] = 1
             else:
                  wordcount[word] += 1
        


    
if __name__ == '__main__':
    
    mainWindow = Window()
# root.mainloop()


  • Could you show the errors you get? Otherwise we can't help you out. – Dhruv Jadhav Mar 01 '21 at 04:09
  • @Dhruv Jadhav look at the new code with the GUI I tried to create inside of it, my mistake I thought it would be easier to post the pure function without the gui – Fallen Dionysus Mar 01 '21 at 04:16
  • how is this different from your previous post? aren't you doing the same thing? – JacksonPro Mar 01 '21 at 04:22
  • @JacksonPro I decided to work backwards from my function to try to find the gui i needed however after creating the correct function I want to try to insert the GUI back in however it doesn't seem to be working, – Fallen Dionysus Mar 01 '21 at 04:24
  • @FallenDionysus I'm sorry, but I didn't get what you are trying to convey. Can you explain to me your program in a little more detail? – JacksonPro Mar 01 '21 at 04:30
  • @JacksonPro so I created a function that allows user to select how many of the most common words they want to display and it will display the results with the required amount however I want a gui to go with it, I need someone to help set up the basic gui for my program – Fallen Dionysus Mar 01 '21 at 04:33

1 Answers1

2

I'll present a general example for you to start with in building your GUI. There are a few items I'd like to comment.

It's not a good idea to import tkinter as tk as well as from tkinter import * as this may lead to confuson later in the development. In general it's preferred to import tkinter as tk as you then always can see which module a widget comes from.

I would advise against the mix of flat and OOP programming styles. As above, it may lead to confusion later.

It's a good idea to use descriptive names, even if you just create and forget widgets, because an error message will tell you the name of the offending object. And also just in general it's easier to get a grip of the application with descriptive names. For example the GUI Buttons could instead be called: self.open_btn and self.exit_btn.

When you are working with files you may consider using the with statement as this adds a layer of security; it won't leave files open even if there is an error.

My example uses a program structure which I often use myself, depending on how I intend to use the program. Pros and cons for different structures are discussed in the thread Best way to structure a tkinter application?

Below is an example you can use as a cornerstone for your efforts if you wish.

import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master):
        super().__init__()  # Call __init__() method in parent (tk.Frame)
        self.bg_image = tk.PhotoImage(file = "images/pilner.png")
        self.background = tk.Label( root, image=self.bg_image) 
        self.background.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
        
        self.open_btn = tk.Button(text='Open File', command=self.open_file)
        self.open_btn.pack(pady=(30,10))
        self.exit_btn = tk.Button(text='Exit', command=master.destroy)
        self.exit_btn.pack()

    def open_file(self):
        with open('Macbeth Entire Play.txt', encoding="utf8") as file:
            self.file_text = file.read()
        # Etc, etc.

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Count words")
    root.geometry('400x400+900+50')
    app = Application(root)
    app.pack(expand=True, fill='both')
    root.mainloop()

Hope this is of help.

figbeam
  • 7,001
  • 2
  • 12
  • 18