Python, I want user to input text file - python

Hello currently I'm working on a word occurrence counter, I created a gui for it where users can type the words and then press the "count" button and it will count the occurence of each word, however I want to make it so user can instead upload a text file and the word occurrence will count the occurence of each word in the text file instead. Does anyone know how to make the transition? I need to know how to change it from user input words to user upload text files.
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)

Use filedialog.askopenfilename method:
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()
Output:

Related

Text label not showing up

I have changed everything on other answers but nothing works.
from tkinter import *
import tkinter as tk
import tkinter
import pynput
from pynput.keyboard import Key, Listener
from tkinter import filedialog
charCount = 0
keys = []
press_value = 0
root = Tk()
my_menu = Menu(root)
root.config(menu=my_menu)
def label1(root):
label = tkinter.Label(root, text = "correct")
label.pack()
def pressOn():
button_1.configure(fg = "Green", text = "ON")
def pressOff():
button_1.configure(fg = "red", text = "OFF")
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.pack(fill=BOTH, expand=1)
def save_location():
location_window = Tk()
var = StringVar()
var.set('No Folder Selected')
locationLabel = Label(location_window, textvariable=var.get())
locationLabel.place(x=70,y=20)
location_window.update()
def browse_button():
filename = filedialog.askdirectory()
print(filename)
var = filename
button2 = Button(location_window, text="Browse", command=browse_button).grid(row=1, column=0)
location_window.title('Save Location')
location_window.iconbitmap('C:/Users/Gaming/Downloads/floppydisk.ico')
location_window.geometry('250x100')
location_window.mainloop()
file_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New...", command=label1)
file_menu.add_command(label="Exit", command=root.quit)
#Create an edit menu item
edit_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Save Location", command=save_location)
edit_menu.add_command(label="Copy", command=label1)
def buttonPress():
global press_value
press_value = press_value + 1
if (press_value % 2) == 0:
pressOff()
else:
pressOn()
button_1 = tkinter.Button(text="OFF", width = '10', height = '10', fg = 'red', command = buttonPress)
button_1.pack(side = 'bottom')
If you click 'edit' and then'save location'. It pops up with a box but should show a label about the directory people can choose by picking the browse button. It is not working though, the label is not showing. Thanks for everyone's help in advance.

Python Tkinter - processing data entered by a user

I want to create a program in Python with Tkinter GUI, and I want it to take string inputs from a user, then I want to do some operations on these strings - in this case, I want to mix parts of two words and get a new word. How can I handle this data entered by a user and use it to receive the result? Below is my code. I couldn't find the answer to this problem and nothing I tried works.
from Tkinter import *
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Mix words")
self.pack(fill=BOTH, expand=1)
menu = Menu(self.master)
self.master.config(menu=menu)
entryLbl1 = Label(self, text="Write the first word: ")
entryLbl1.pack()
self.entrytext1 = StringVar()
Entry(self, textvariable=self.entrytext1).pack()
self.buttontext1 = StringVar()
self.buttontext1.set("OK")
Button(self, textvariable=self.buttontext1, command=self.clicked1).pack()
self.label1 = Label(self, text="")
self.label1.pack()
global user_entry1
user_entry1 = self.entrytext1.get()
entryLbl2 = Label(self, text="Write the second word: ")
entryLbl2.pack()
self.entrytext2 = StringVar()
Entry(self, textvariable=self.entrytext2).pack()
self.buttontext2 = StringVar()
self.buttontext2.set("OK")
Button(self, textvariable=self.buttontext2, command=self.clicked2).pack()
self.label2 = Label(self, text="")
self.label2.pack()
global user_entry2
user_entry2 = self.entrytext2.get()
entryLbl3 = Label(self, text="Result: ")
entryLbl3.pack()
self.buttontext3 = StringVar()
self.buttontext3.set("Result")
Button(self, textvariable=self.buttontext1, command=self.clicked3).pack()
self.label3 = Label(self, text="")
self.label3.pack()
def clicked1(self):
input = self.entrytext1.get()
self.label1.configure(text=input)
def clicked2(self):
input = self.entrytext2.get()
self.label2.configure(text=input)
def clicked3(self):
self.user_entry1 = user_entry1
self.user_entry2 = user_entry2
first2a = user_entry1[0:2]
rest_a = user_entry1[2:]
first2b = user_entry2[0:2]
rest_b = user_entry2[2:]
input = first2b + rest_a + " " + first2a + rest_b
self.label3.configure(text=input)
root = Tk()
root.iconbitmap("py.ico")
root.geometry("600x300")
app = Window(root)
root.mainloop()
You need Entry() objects.
The following will show two Entry widgets and a Button.
When the button is pressed, the contents of both of the Entry objects will be printed to the console:
import sys
# Determine if you're running Python 3
is_py_3 = sys.version[0] == '3'
# Import Tkinter for the correct version of Python
if is_py_3:
from tkinter import Button, Entry, Tk
else:
from Tkinter import Button, Entry, Tk
class GUI:
def __init__(self):
# Set up the "Root" or "Parent" of the window.
self.root = Tk()
# Set up two "Entry" widgets.
self.entry1 = Entry(self.root)
self.entry1.insert(0, "Enter something here.")
self.entry2 = Entry(self.root)
self.entry2.insert(0, "and here...")
# Set up a button to handle the event.
self.button = Button(self.root, text="CLICK ME", command=self.onClicked)
self.entry1.pack()
self.entry2.pack()
self.button.pack()
def onClicked(self):
# Print the contents of the entry widgets.
s1 = self.entry1.get()
s2 = self.entry2.get()
print(s1, s2)
app = GUI()
app.root.mainloop()

How to print through local or network printer in tkinter

I want to select one of installed printer on my computer and print through it but my combobox doesn't display the printers on my machine but rather print to my terminal in my IDE .
Have been trying this for days with arriving at the solution to do this.Have installed the win32print module to after reading about it.This my code below:
from tkinter import *
from tkinter import ttk
import win32print
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,
textvariable=installed_printer).pack()
BUTTON = ttk.Button(pt, text="refresh",
command=installed_printer).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10)
def INFO():
print(T2.get("1.0", END))
Print_Button = Button(root, text ="Print", command =
INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()
How can i achieve this as i want to print the content in my Text box with tkinter framework.
Is this what you wanted to create?
from tkinter import *
from tkinter import ttk
import win32api
import win32print
import tempfile
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
printerdef = ''
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
var1 = StringVar()
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,textvariable=var1)
print_list = []
printers = list(win32print.EnumPrinters(2))
for i in printers:
print_list.append(i[2])
print(print_list)
# Put printers in combobox
PRCOMBO['values'] = print_list
PRCOMBO.pack()
def select():
global printerdef
printerdef = PRCOMBO.get()
pt.destroy()
BUTTON = ttk.Button(pt, text="Done",command=select).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10, wrap=WORD)
def INFO():
printText = T2.get("1.0", END)
print(printText)
print(printerdef)
filename = tempfile.mktemp(".txt")
open(filename, "w").write(printText)
# Bellow is call to print text from T2 textbox
win32api.ShellExecute(
0,
"printto",
filename,
'"%s"' % win32print.GetDefaultPrinter(),
".",
0
)
Print_Button = Button(root, text ="Print", command=INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()

Find and change the color of a word in a text box Tkinter

I am making a development environment type program with python and have a basic working program but I have a problem. I want to highlight certain words like import in a different color, like most development environments do but it wont work!
from tkinter import filedialog
from gameplay import *
from tkinter import *
import msvcrt as m
import os
openfileloc = ""
def combine_funcs(*funcs):
def combined_func(*args, **kwargs):
for f in funcs:
f(*args, **kwargs)
return combined_func
def load_file():
rootFd = Tk()
rootFd.withdraw()
file_path = filedialog.askopenfilename()
data = open(file_path, "r").read()
txtFd.delete('1.0', END)
txtFd.insert('1.0', data)
openfile = data
openfileloc = file_path
def save_file_dialog():
rootFd = Tk()
rootFd.withdraw()
wr = filedialog.asksaveasfile(mode='w', defaultextension=".br")
if wr.name != '':
wr.write(txtFd.get('1.0', "end"))
openfileloc = wr.name
wr.close()
def save_file():
if os.path.isfile(openfileloc):
os.remove(file_path)
wr = open(openfileloc, "w").write(txtFd.get('1.0', "end"))
else:
save_file_dialog()
def new_file():
txtFd.delete('1.0', END)
openfile = ""
openfileloc = ""
# HEY STACKOVERFLOW PROBLEM IS HERE
def highlightKeywords():
text = txtFd,get('1.0', 'end')
KeywordSet1 = ['import', 'if'] # Hilighted in Yellow
for i in range(len(text)):
if KeywordSet[i] in text:
txtFd.highlight_pattern(KeywordSet1[i], "yellow")
root = Tk()
root.title("GameBox Engine Editior - 0.0a")
menubar = Menu(root)
#Menu
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=new_file)
filemenu.add_command(label="Open", command=load_file)
filemenu.add_command(label="Save", command=save_file)
filemenu.add_command(label="Save as...", command=save_file_dialog)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
txtFd = Text(root)
txtFd.pack()
root.mainloop()
# THIS IS WHERE I CALL THE FUNCTION
running = True
while(running):
m.getch()
highlightKeywords()
There are no errors, it just does not work. Can you help me?
Use (from http://effbot.org/tkinterbook/text.htm)
text.tag_configure('color', foreground='blue')
text.insert(END, "This is blue\n", 'color')
## you can also use relative position
text.tag_add('color', "1.0", "1.4")

Tkinter Python GUI Issues

Below is my code, it runs but I'm not sure how to get the "Run text" button to prompt me to open text file in new window, currently a new window appears with a "Quit" button, nothing else.
import tkFileDialog
import Tkinter as tk
from Tkinter import *
import logging
logging.basicConfig(filename= "log_file.txt", filemode = "w", level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
class HomeScreen:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'Run Text', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()
def openFile(self):
openfile = tkFileDialog.askopenfile().read()
text= open(openfile, 'r').read()
T.insert(1.0, openfile)
T = Text(height=10, width=100)
T.pack()
T.insert(END, "Select file to input")
B = Button(root, text="Open", command=openFile)
B.pack()
mainloop()
return
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Quit(self.newWindow)
class Quit:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = HomeScreen(root)
app = Quit(root)
root.mainloop()
if __name__ == '__main__':
main()
I'm sure my code is very messy as I'm just a beginner, some parts may not be needed, any advice would be greatly appreciated.
I've simplified your code a bit, but I've also enhanced it a little. I use askopenfilename rather than askopenfile, so we can get the file name and display it in the titlebar of each Toplevel window containing a Text widget.
import tkFileDialog
import Tkinter as tk
class HomeScreen:
def __init__(self, master):
self.master = master
frame = tk.Frame(master)
frame.pack()
button = tk.Button(frame, text='Show Text', width=25, command=self.open_file)
button.pack()
button = tk.Button(frame, text='Quit', width=25, command=master.destroy)
button.pack()
master.mainloop()
def open_file(self):
filename = tkFileDialog.askopenfilename()
if not filename:
#User cancelled
return
with open(filename) as f:
filedata = f.read()
window = tk.Toplevel(self.master)
window.title(filename)
text = tk.Text(window, height=10, width=100)
text.pack()
text.insert(1.0, filedata)
def main():
root = tk.Tk()
HomeScreen(root)
if __name__ == '__main__':
main()
To display the text file one word at a time you can replace the open_file method with the version below. You'll also need to add the show_word method. I'm not claiming that this is the best way to achieve this effect, but at least it works. :)
def show_word(self, word):
self.text.delete(1.0, tk.END)
self.text.insert(tk.END, word)
def open_file(self):
filename = tkFileDialog.askopenfilename()
if not filename:
#User cancelled
return
with open(filename) as f:
filedata = f.read()
words = filedata.split()
window = tk.Toplevel(self.master)
window.title(filename)
self.text = text = tk.Text(window, height=10, width=100)
text.pack()
delta = 1000 #in millseconds
delay = 0
for word in words:
window.after(delay, lambda word=word: self.show_word(word))
#print word
delay += delta
If you want that "Run text" open's a file dialog change called method:
self.button1 = tk.Button(self.frame, text = 'Run Text', width = 25, command = self.openFile)

Categories