【问题标题】:Python, I want user to input text filePython,我希望用户输入文本文件
【发布时间】: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获取文件路径?

标签: python tkinter word


【解决方案1】:

使用filedialog.askopenfilename方法:

import tkinter as tk
from tkinter import filedialog
from collections import Counter

class App(object):
    def __init__(self):

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

    def open_file(self):
        filename = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('text files','*.txt'), ('all files','*.*')))
        with open(filename, 'r') as f:
            self.lbl.configure(text=f'{Counter(f.read().split())}')

App()

输出:

【讨论】:

  • 谢谢,这对我的问题很有帮助。祝你有美好的一天
猜你喜欢
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 2017-04-14
相关资源
最近更新 更多