【发布时间】:2021-02-24 14:48:05
【问题描述】:
您好,目前我正在开发一个单词出现计数器,我为它创建了一个 gui,用户可以在其中输入单词,然后按“计数”按钮,它会计算每个单词的出现次数,但是我想做它使用户可以改为上传文本文件,并且单词出现将计算文本文件中每个单词的出现次数。有谁知道如何进行过渡?我需要知道如何将其从用户输入词更改为用户上传文本文件。
import tkinter as tk
from tkinter import *
from collections import Counter
#Functions
def countWords(s):
signos = [',', '.', ';', ':']
cleanstr = ''
for letra in s.lower():
if letra in signos:
cleanstr += ''
else:
cleanstr += letra
strlist = cleanstr.split(' ')
return dict(Counter(strlist))
def button_count():
text = mainWindow.e2.get()
count = countWords(text)
myLabel = Label(root, text=count)
myLabel.pack()
#Graphics
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, root):
self.root = root
self.e2 = tk.StringVar()
self.e = tk.Entry(root, textvariable=self.e2, width=35, borderwidth=5)
self.e.pack()
self.button = Button(root, text="Count words", command=button_count)
self.button.pack()
self.exit_button = Button(root, text="Exit", command=root.quit)
self.exit_button.pack()
if __name__ == '__main__':
mainWindow = Window(root)
【问题讨论】:
-
使用
tkinter.filedialog.askopenfilename获取文件路径?