After defining my word count method thanks to another member, I am now creating a GUI to go along with it. I have created three buttons, one for browsing for a file, one for counting the words and lines in a file, and one for exiting.
My question is, how do I make these buttons do things? I am trying to make the "Browse for a file" run the filename = fileopenbox() line, and the "Count" button run the word_count() method.
Here is what the code looks like:
from tkinter import *
from easygui import fileopenbox
root = Tk()
root.title("Word Counter")
root.geometry("500x500")
app = Frame(root)
app.grid()
button1 = Button(app, text = "Browse for a file")
button1.grid()
button2 = Button(app)
button2.grid()
button2.configure(text ="Count the file")
button3 = Button(app)
button3.grid()
button3["text"] = "Exit"
root.mainloop()
def word_count(filename):
filename = fileopenbox()
if not filename.endswith(('.txt', '.py', '.java')):
print('Are you trying to annoy me? How about giving me a TEXT or SOURCE CODE file, genius?')
return
with open(filename) as f:
n_lines = 0
n_words = 0
for line in f:
n_lines += 1
n_words += len(line.split())
print('Your file has {} lines, and {} words'.format(n_lines, n_words))
You have to pass the reference to the function you want to execute as the command option. Since you are divinding the task in two steps (one button to ask for the file name, and another one to count the lines and the words), I'd suggest you to create a class to wrap everything.
Besides, I suggest you to remove the dependency of easygui - since it is a project that is not longer maintained - and replace it with filedialog.askopenfilename, which is part of the standard library:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showwarning, showinfo
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.filename = None
button1 = Button(self, text="Browse for a file", command=self.askfilename)
button2 = Button(self, text ="Count the file", command=self.word_count)
button3 = Button(self, text="Exit", command=master.destroy)
button1.grid()
button2.grid()
button3.grid()
self.grid()
def askfilename(self):
filename = askopenfilename()
if not filename.endswith(('.txt', '.py', '.java')):
showwarning('Are you trying to annoy me?', 'How about giving me a TEXT or SOURCE CODE file, genius?')
else:
self.filename = filename
def word_count(self):
if self.filename:
with open(self.filename) as f:
n_lines = 0
n_words = 0
for line in f:
n_lines += 1
n_words += len(line.split())
showinfo('Result', 'Your file has {} lines, and {} words'.format(n_lines, n_words))
else:
showwarning('No file selected', 'Select a file first')
root = Tk()
root.title("Word Counter")
root.geometry("500x500")
app = App(root)
root.mainloop()
Related
I'm new to Tkinter and I'm trying to create a simple Button that opens a file dialog box, where the user chooses which CSV file to open. Under the button there is a label that should display the file path for the file that was opened.
When I click on the button once, everything works as expected. However, if I click on it a second time and select a different file, the new filepath overlaps with the previous one, instead of replacing it.
Here is the code for the implementation function (please let me know if you need more bits of code for context):
def open_csv_file():
global df
global filename
global initialdir
initialdir = r"C:\Users\stefa\Documents\final project models\Case A"
filename = filedialog.askopenfilename(initialdir=initialdir,
title='Select a file', filetypes = (("CSV files","*.csv"),("All files","*.*")))
df = pd.read_csv(os.path.join(initialdir,filename))
lbl_ok = tk.Label(tab2, text = ' ') #tab2 is a ttk.Notebook tab
lbl_ok.config(text='Opened file: ' + filename)
lbl_ok.grid(row=0,column=1)
Here is how to do it with .config(), create the label instance just once (can then grid as much as you want but probably just do that once too), then just configure the text:
from tkinter import Tk, Button, Label, filedialog
def open_file():
filename = filedialog.askopenfilename()
lbl.config(text=f'Opened file: {filename}')
root = Tk()
Button(root, text='Open File', command=open_file).grid()
lbl = Label(root)
lbl.grid()
root.mainloop()
You can use a StringVar for this. Here is an example that may help you:
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.geometry('200x200')
def openCsv():
csvPath.set(askopenfilename())
csvPath = StringVar()
entry = Entry(root, text=csvPath)
entry.grid(column=0, row=0)
btnOpen = Button(root, text='Browse Folder', command=openCsv)
btnOpen.grid(column=1, row=0)
root.mainloop()
I am new to Python and obviously missing something important when working with checkbuttons. Here's the idea behind my program: I select a file manually and then, depending on whether the checkbox is checked or not, trigger either one calculation sequence or another using a button. To achieve this, I wanted to verify the state of the checkbox using the .get() command.
What I've found is that only one sequence is triggered all the time independently of the state of the checkbox. .get() is not updated when I click on the checkbox. What am I doing wrong? Any help will be greatly appreciated.
from tkinter import *
from tkinter import filedialog
import tkinter as tk
master = Tk()
root = tk.Tk()
col_sep = "\t"
col_h_b = [] # field column for background
col_m_b = [] # magnetization column for background
def choose_b_file():
root.fileName_b = filedialog.askopenfilename(filetypes=((".dat files", "*.dat"), ("All files", "*.*")))
with open(root.fileName_b, 'r') as f:
for line in f:
if line[0] != "#":
linedata = [float(line.split(col_sep)[i]) for i in range(len(line.split(col_sep)))]
col_h_b.append(linedata[4])
col_m_b.append(linedata[5])
print(f.name)
offset = BooleanVar()
checkbox = tk.Checkbutton(root, text="offset subtraction", variable=offset,onvalue=1, offvalue=0)
checkbox.pack()
def plot():
if offset.get() == 1:
#some mathematical operations and graph plotting
else:
#other mathematical operations and graph plotting
def close_window():
exit()
b_data = Button(master, text="Background", width=20, command=choose_b_file)
m_minus_b = Button(master, text="Plot", width=5, command=plot)
quit = Button(master, text="Quit", width=5, command=close_window)
b_data.pack()
m_minus_b.pack()
quit.pack()
root.mainloop()
You are mostly messing parents widgets root and master.
Do you need to have a separate window for the checkbox ?
Otherwise the quick fix is to replace root by master in the checkbox creation :
checkbox = tk.Checkbutton(root, text="offset subtraction" ...)
You can also simplify the boolean stuff, the default behavior for the checkbutton is to use 0 and 1, and remove the master or the root, choose only one.
from tkinter import *
from tkinter import filedialog
root = Tk()
col_sep = "\t"
col_h_b = [] # field column for background
col_m_b = [] # magnetization column for background
def choose_b_file():
root.fileName_b = filedialog.askopenfilename(filetypes=((".dat files", "*.dat"), ("All files", "*.*")))
with open(root.fileName_b, 'r') as f:
for line in f:
if line[0] != "#":
linedata = [float(line.split(col_sep)[i]) for i in range(len(line.split(col_sep)))]
col_h_b.append(linedata[4])
col_m_b.append(linedata[5])
print(f.name)
def plot():
if offset.get() == 1:
print('True')
#some mathematical operations and graph plotting
else:
print('False')
#other mathematical operations and graph plotting
def close_window():
exit()
offset = IntVar()
checkbox = Checkbutton(root, text="offset subtraction", variable=offset)
checkbox.pack()
b_data = Button(root, text="Background", width=20, command=choose_b_file)
m_minus_b = Button(root, text="Plot", width=5, command=plot)
quit = Button(root, text="Quit", width=5, command=close_window)
b_data.pack()
m_minus_b.pack()
quit.pack()
root.mainloop()
This GUI allows the user to open the file browser and select the files you need, show it on the field blank and then open the file once open is pressed. I'm new to python and had tried placing print tkFileDialog.askopenfilename() at the self.filename but this results in a syntax error. Please help. Thanks!
My question is as follows:
1) Why does my file browser open twice upon pressing the "file browser" button.
2) Also, how do I state the directory of the file selected in the file blank instead of in the python command prompt?
I would like to open the file in the future after pressing the ok button.
from Tkinter import *
import csv
import tkFileDialog
class Window:
def __init__(self, master):
self.filename=""
csvfile=Label(root, text="Load File:").grid(row=1, column=0)
bar=Entry(master).grid(row=1, column=1)
#Buttons
y=12
self.cbutton= Button(root, text="OK", command=self.process_csv) #command refer to process_csv
y+=1
self.cbutton.grid(row=15, column=3, sticky = W + E)
self.bbutton= Button(root, text="File Browser", command=self.browsecsv) #open browser; refer to browsecsv
self.bbutton.grid(row=1, column=3)
def browsecsv(self):
from tkFileDialog import askopenfilename
Tk().withdraw()
self.filename = askopenfilename()
print tkFileDialog.askopenfilename() # print the file that you opened.
def callback():
abc = askopenfilename()
execfile("input.xlsx")
def process_csv(self):
if self.filename:
with open(self.filename, 'rb') as csvfile:
logreader = csv.reader(csvfile, delimiter=',', quotechar='|')
rownum=0
for row in logreader:
NumColumns = len(row)
rownum += 1
Matrix = [[0 for x in xrange(NumColumns)] for x in xrange(rownum)]
root = Tk()
window=Window(root)
root.mainloop()
Your both questions are connected. The problem is in your browsecsv(self) method. Your directory is already stored in self.filename, no need to call askopenfilename() again. That's the reason why the file browser opens twice. Moreover, to set text in your Entry, you need to assign it a text variable.
self.entryText = StringVar()
self.bar = Entry(root, textvariable=self.entryText ).grid(row=1, column=1)
Then, you can assign it to the Entry in your method:
def browsecsv(self):
from tkFileDialog import askopenfilename
Tk().withdraw()
self.filename = askopenfilename()
self.entryText.set(self.filename)
I'm having trouble returning a variable from a tkinter Button command. Here is my code:
class trip_calculator:
def __init__(self):
file = self.gui()
def gui(self):
returned_values = {}
def open_file_dialog():
returned_values['filename'] = askopenfilename()
root = Tk()
Button(root, text='Browse', command= open_file_dialog).pack()
filepath = returned_values.get('filename')
root.mainloop()
return filepath
root.quit()
I just want to return the filepath of a text file. The tkinter window is open and I can browse and choose the file but it then doesn't return the path.
The way your code is now, filepath is assigned its value before your window even appears to the user. So there's no way the dictionary could contain the filename that the user eventually selects. The easiest fix is to put filepath = returned_values.get('filename') after mainloop, so it won't be assigned until mainloop ends when the user closes the window.
from Tkinter import *
from tkFileDialog import *
class trip_calculator:
def gui(self):
returned_values = {}
def open_file_dialog():
returned_values['filename'] = askopenfilename()
root = Tk()
Button(root, text='Browse', command= open_file_dialog).pack()
root.mainloop()
filepath = returned_values.get('filename')
return filepath
root.quit()
print(trip_calculator().gui())
I'm doing some work with GUI in python. I'm using the Tkinter library.
I need a button, which will open a .txt file and do this bit of processing:
frequencies = collections.defaultdict(int) # <-----------------------
with open("test.txt") as f_in:
for line in f_in:
for char in line:
frequencies[char] += 1
total = float(sum(frequencies.values())) #<-------------------------
I started with:
from Tkinter import *
import tkFileDialog,Tkconstants,collections
root = Tk()
root.title("TEST")
root.geometry("800x600")
button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
fileName = ''
def openFile():
fileName = tkFileDialog.askopenfile(parent=root,title="Open .txt file", filetypes=[("txt file",".txt"),("All files",".*")])
Button(root, text = 'Open .txt file', fg = 'black', command= openFile).pack(**button_opt)
frequencies = collections.defaultdict(int) # <-----------------------
with open("test.txt") as f_in:
for line in f_in:
for char in line:
frequencies[char] += 1
total = float(sum(frequencies.values())) #<-------------------------
root.mainloop()
Now I don't know how to assemble my code so it runs when the button is pressed.
The main problem was tkFileDialog.askopenfile() returns an open file rather than a file name. This following seemed to be more-or-less working for me:
from Tkinter import *
import tkFileDialog, Tkconstants,collections
root = Tk()
root.title("TEST")
root.geometry("800x600")
def openFile():
f_in = tkFileDialog.askopenfile(
parent=root,
title="Open .txt file",
filetypes=[("txt file",".txt"),("All files",".*")])
frequencies = collections.defaultdict(int)
for line in f_in:
for char in line:
frequencies[char] += 1
f_in.close()
total = float(sum(frequencies.values()))
print 'total:', total
button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
fileName = ''
Button(root, text = 'Open .txt file',
fg = 'black',
command= openFile).pack(**button_opt)
root.mainloop()
For quickly creating simple GUI programs I highly recommend EasyGUI, a fairly powerful yet simple Tk--based Python module for doing such things.
Try something laid out a bit like this:
class my_app():
def __init__():
self.hi_there = Tkinter.Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=Tkinter.LEFT)
def say_hi():
# do stuff
You also may want to read:
This tutorial on Tkinter,
And this one.
EDIT: The OP wanted an example with his code (I think) so here it is:
from Tkinter import *
import tkFileDialog,Tkconstants,collections
class my_app:
def __init__(self, master):
frame = Tkinter.Frame(master)
frame.pack()
self.button_opt = {'fill': Tkconstants.BOTH, 'padx': 66, 'pady': 5}
self.button = Button(frame, text = 'Open .txt file', fg = 'black', command= self.openFile).pack(**button_opt)
self.calc_button = Button(frame, text = 'Calculate', fg = 'black', command= self.calculate).pack()
self.fileName = ''
def openFile():
fileName = tkFileDialog.askopenfile(parent=root,title="Open .txt file", filetypes=[("txt file",".txt"),("All files",".*")])
def calculate():
############################################### *See note
frequencies = collections.defaultdict(int) # <-----------------------
with open("test.txt") as f_in:
for line in f_in:
for char in line:
frequencies[char] += 1
total = float(sum(frequencies.values())) #<-------------------------
################################################
root = Tk()
app = App(root)
root.title("TEST")
root.geometry("800x600")
root.mainloop()
*Note: Nowhere in your code did I see where collections came from so I wasn't quite sure what to do with that block. In this example I have set it to run on the
In your openFile() function, just after you ask the user for a file name, put your code!