您好,我创建了这个函数,允许您计算麦克白剧本中的前X个单词,但是我想在我创建的gui中显示结果,不知道是否有人可以告诉我如何计算?我已经创建了该函数并对其进行了测试,但我不了解python gui,每当我尝试创建它时,都会遇到大量错误
#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()
在构建GUI时,我将为您提供一个通用示例。有几点我想评论一下
这不是一个好主意
import tkinter as tk
以及from tkinter import *
,因为这可能会在以后的开发中导致混乱。一般来说,最好使用import tkinter as tk
,因为这样您就可以始终看到小部件来自哪个模块我建议不要混合使用平面和面向对象编程风格。如上所述,这可能会导致以后的混乱
使用描述性名称是个好主意,即使您只是创建并忘记了小部件,因为错误消息会告诉您有问题的对象的名称。而且一般来说,使用描述性名称更容易掌握应用程序。例如,GUI按钮可以改为:
self.open_btn
和self.exit_btn
当您使用文件时,您可以考虑使用^ {CD6>}语句,因为这增加了一层安全性;即使出现错误,它也不会使文件保持打开状态
我的例子使用了一个我经常自己使用的程序结构,这取决于我打算如何使用该程序。线程Best way to structure a tkinter application?中讨论了不同结构的优缺点
下面是一个例子,如果你愿意,你可以用它作为你努力的基石
希望这能有所帮助
相关问题 更多 >
编程相关推荐