How to Show File Path with Browse Button in Python / Tkinter - python

Working with Python and Tkinter, I have been trying to find out the way to show the file_path beside the Browse Button but unable to do so.
Here is my code:
import os
from tkFileDialog import askopenfilename
from Tkinter import *
content = ''
file_path = ''
#~~~~ FUNCTIONS~~~~
def open_file():
global content
global file_path
filename = askopenfilename()
infile = open(filename, 'r')
content = infile.read()
file_path = os.path.dirname(filename)
return content
def process_file(content):
print content
#~~~~~~~~~~~~~~~~~~~
#~~~~~~ GUI ~~~~~~~~
root = Tk()
root.title('Urdu Mehfil Ginti Converter')
root.geometry("598x120+250+100")
mf = Frame(root)
mf.pack()
f1 = Frame(mf, width=600, height=250)
f1.pack(fill=X)
f2 = Frame(mf, width=600, height=250)
f2.pack()
file_path = StringVar
Label(f1,text="Select Your File (Only txt files)").grid(row=0, column=0, sticky='e')
Entry(f1, width=50, textvariable=file_path).grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse", command=open_file).grid(row=0, column=27, sticky='ew', padx=8, pady=4)
Button(f2, text="Process Now", width=32, command=lambda: process_file(content)).grid(sticky='ew', padx=10, pady=10)
root.mainloop()
#~~~~~~~~~~~~~~~~~~~
Kindly guide me as how I can show the file path along with the "Browse Button" button after the user selects the file as shown in this image.
Thanks in advance!

First, change this line:
Entry(f1, width=50, textvariable=file_path).grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
to this:
entry = Entry(f1, width=50, textvariable=file_path)
entry.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Then, in the open_file() function, add these two lines, just before the return:
entry.delete(0, END)
entry.insert(0, file_path)
Explanation:
First, we give the entry a name, so that it can be modified.
Then, in the open_file() function we clear it and add the text for the file-path.

Here is a diff that fixes instead the file_path, i.e. the StringVar() usage:
--- old.py 2016-08-10 18:22:16.203016340 +0200
+++ new.py 2016-08-10 18:24:59.115328029 +0200
## -4,7 +4,6 ##
content = ''
-file_path = ''
#~~~~ FUNCTIONS~~~~
## -16,7 +15,7 ##
filename = askopenfilename()
infile = open(filename, 'r')
content = infile.read()
- file_path = os.path.dirname(filename)
+ file_path.set(os.path.dirname(filename))
return content
def process_file(content):
## -40,7 +39,7 ##
f2 = Frame(mf, width=600, height=250)
f2.pack()
-file_path = StringVar
+file_path = StringVar(root)
Label(f1,text="Select Your File (Only txt files)").grid(row=0, column=0, sticky='e')

Related

can't insert default text into TKinter

So I am creating a text editor using TKinter. I have the basics down and now I am trying to create a button where when you press it, you select a file and it opens it. From what I have seen the insert method would be best for Entry widget. But i am using Label widget and it does not work for some reason. Here is my code so far:
import sys
import tkinter as tk
frame = tk.Tk()
frame.title("Fake Google Docs")
frame.geometry('800x600')
inputtxt = tk.Text(frame,
height = 25,
width = 90)
inputtxt.pack()
global file
#this is function to be executed when u press first button
def printInput():
filename = input("Name of the file make sure you end with .txt")
file = open(filename, 'w')
result=inputtxt.get("1.0","end")
file.write(result)
file.close()
#this is function to be executed for open new file thing
def printInputnew():
filenamemm = input("Name of the file make sure you end with .txt")
file = open(filenamemm, 'w')
result=inputtxt.get("1.0","end")
file.write("")
file.close()
def openfile():
filenamem = input("Name of the file you want to open")
tru=open(filenamem)
if tru== False:
sys.exit()
else:
f = open(filenamem, "r")
for x in f:
print(x)
name=str(x)
text = tk.StringVar()
text.set(name)
#button 1
printButton = tk.Button(frame,
text = "Save to text file",
command = printInput)
printButton.pack()
printButtonl = tk.Button(frame,
text = "open a file",
command = openfile)
printButtonl.pack()
#button 2
printButton = tk.Button(frame,
text = "Open new file",
command = printInputnew)
printButton.pack()
#open the text box
lbl = tk.Label(frame, textvariable = "")
lbl.pack()
#finish code
frame.mainloop()
Could someone else suggest a method for inserting text into this widget?
Here it is:
import sys
import tkinter as tk
from tkinter import filedialog
frame = tk.Tk()
frame.title("Fake Google Docs")
frame.geometry('800x600')
inputtxt = tk.Text(frame,
height=25,
width=90)
inputtxt.pack()
global file
mask = [("Text and Python files", "*.txt *.py *.pyw *.rcad"),
("HTML files", "*.htm"),
("All files", "*.*")]
# this is function to be executed when u press first button
def printInput():
filename = input("Name of the file make sure you end with .txt")
file = open(filename, 'w')
result = inputtxt.get("1.0", "end")
file.write(result)
file.close()
# this is function to be executed for open new file thing
def printInputnew():
filenamemm = input("Name of the file make sure you end with .txt")
file = open(filenamemm, 'w')
result = inputtxt.get("1.0", "end")
file.write("")
file.close()
def openfile():
filenamem = filedialog.askopenfilename(filetypes=mask)
tru = open(filenamem)
if tru == False:
sys.exit()
else:
f = open(filenamem, "r")
inputtxt.delete(0.0, 'end')
inputtxt.insert('end', f.read())
# button 1
printButton = tk.Button(frame,
text="Save to text file",
command=printInput)
printButton.pack()
printButtonl = tk.Button(frame,
text="open a file",
command=openfile)
printButtonl.pack()
# button 2
printButton = tk.Button(frame,
text="Open new file",
command=printInputnew)
printButton.pack()
# open the text box
lbl = tk.Label(frame, textvariable="")
lbl.pack()
# finish code
frame.mainloop()
I changed this block of code:
def openfile():
filenamem = filedialog.askopenfilename(filetypes=mask)
tru = open(filenamem)
if tru == False:
sys.exit()
else:
f = open(filenamem, "r")
inputtxt.delete(0.0, 'end')
inputtxt.insert('end', f.read())
It opens a window that ask you which file you want to open. askopenfilename method returns a string path to selected file. Then you just read whole file, delete whole text that you had in your tk.Text object and paste there text from opened file. That is all :)
And please, next time watch some guides about tkinter before asking and read about PEP8.

tkinter :not changing the label value when it goes throuh for loop, it dispalying the ending value only

I have Created a tkinter UI for some file processing python script. When we choose a directory, then it will return the files in the directory, and then it will takes the each files by using a for loop and it will display 'processed files' for reach iteration. hence the Processed files number have to be change from 0 to the total number of files in the directory.
import os
import time
from tkinter import *
from tkinter import filedialog
import tkinter as tk
root = Tk()
root.title("Demo")
root.geometry('550x300')
root.resizable(width=False, height=False)
def start(userInput,):
e1.configure(text=userInput.get())
print(userInput.get())
ll.destroy()
e1.destroy()
browse_btn.destroy()
st_btn.destroy()
folder_path = userInput.get()
path = folder_path
TEST_IMAGE_PATHS = [f for f in os.listdir(path) if f.endswith('.jpg')]
# print(TEST_IMAGE_PATHS)
Total_No_Files = len(TEST_IMAGE_PATHS)
II_l2_prompt="Total number of files "
II_l2 = Label(root, text=II_l2_prompt, width=22, font=("Arial", 11))
II_l2.place(x=30, y=160, height=25)
II_l3_prompt = str(Total_No_Files)
II_l3 = Label(root, text=II_l3_prompt, width=len(II_l3_prompt), font=("Arial", 11))
II_l3.place(x=240, y=160, height=25)
II_l4_prompt="Processed files "
II_l4 = Label(root, text=II_l4_prompt, width=22, font=("Arial", 11))
II_l4.place(x=30, y=210, height=25)
my_string_var = tk.StringVar()
II_l5_prompt=0
my_string_var.set(II_l5_prompt)
II_l5 = Label(root, textvariable=my_string_var, width=len(str(my_string_var)), font=("Arial", 11))
II_l5.place(x=240, y=210, height=25)
for e in TEST_IMAGE_PATHS:
II_l5_prompt += 1
# time.sleep(2)
my_string_var.set(II_l5_prompt)
def browse(userInput):
File_path = filedialog.askdirectory(title='Select Folder')
if File_path:
File_name = os.path.basename(File_path)
# print(File_name)
e1.delete(0, "end") # delete all the text in the entry
e1.insert(0, File_path)
e1.config(fg='black')
ll = Label(root, text="Path", font=("Arial", 12))
ll.place(x=30, y=110, height=25, width=39)
userInput = StringVar()
e1 = Entry(root,bd=1, textvariable=userInput,width=35, font=("Arial", 12))
e1.insert(0, 'Choose')
e1.config(fg='grey')
e1.bind('<Return>', (lambda event: browse(userInput)))
e1.place(x=80, y=110, height=25)
browse_btn = Button(root, text='Browse',width="10", height=5, bd=0, bg="grey",fg='white', command=(lambda: browse(userInput)))
browse_btn.place(x=420, y=105, height=35)
st_btn = Button(root, text='Start',width="10", height=5, bd=0,bg="grey",fg='white', command=(lambda: start(userInput,)))
st_btn.place(x=150, y=200, height=35)
root.mainloop()
But here the 'Processed files' field is returning the last file number instead of changing the label from 1st file number to last in the directory. How can i solve this issue?
The window will update when it's idle. Here it will queue all changes to the GUI until all processing is done and then update the window after the for loop exits. Therefore you will only see the last state.
You can force root to update with root.update() or root.update_idletasks():
root.update() # Update GUI after removing labels & buttons
for e in TEST_IMAGE_PATHS:
II_l5_prompt += 1
my_string_var.set(II_l5_prompt)
root.update_idletasks() # Update GUI after changing II_l5_prompt
time.sleep(2)
I'm not sure why root.update_idletasks() doesn't work when I use it before the for loop, but root.update() works.

Text not being saved in text file on enter-key press using Tkinter

I am building a chat GUI. On enter-key press, I want the text fields to be shown on the text box as well as be saved in a file. I do not want to use separate button. It is being shown in the text box correctly but not getting saved in the file. Please tell me how can it be done. This is my first time using tkinter.
from Tkinter import *
root = Tk()
frame = Frame(root, width=300, height=1000)
frame.pack(side=BOTTOM)
#username entry
L1 = Label(frame, text="User Name")
L1.pack(side = LEFT)
input_username = StringVar()
input_field1 = Entry(frame, text=input_username, width=10)
input_field1.pack(side=LEFT, fill=X)
#addresee entry
L2 = Label(frame, text="#")
L2.pack(side = LEFT)
input_addresee = StringVar()
input_field2 = Entry(frame, text=input_addresee, width=10)
input_field2.pack(side=LEFT, fill=X)
#user comment entry
L3 = Label(frame, text="Comment")
L3.pack(side = LEFT)
input_usertext = StringVar()
input_field3 = Entry(frame, text=input_usertext, width=100)
input_field3.pack(side=LEFT, fill=X)
#write to a file
def save():
text = input_field1.get() + input_field2.get() + input_field3.get()
with open("test.txt", "w") as f:
f.write(text)
#chat box
chats = Text(root)
chats.pack()
def Enter_pressed(event):
input_get_name = input_field1.get()
print(input_get_name)
chats.insert(INSERT, '%s : ' % input_get_name)
input_username.set('')
input_get_add = input_field2.get()
print(input_get_add)
chats.insert(INSERT, '#%s : ' % input_get_add)
input_addresee.set('')
input_get_comment = input_field3.get()
print(input_get_comment)
chats.insert(INSERT, '%s\n' % input_get_comment)
input_usertext.set('')
save()
frame2 = Frame(root)
L2_1 = Label(frame2, text="All chats")
L2_1.pack(side = TOP)
input_field1.bind(Enter_pressed)
input_field2.bind(Enter_pressed)
input_field3.bind("<Return>", Enter_pressed)
frame2.pack()
root.mainloop()
As you said you are setting the input fields to blank
Here's the solution:
def save(text):
with open("test.txt", "w") as f:
f.write(text)
And when calling save:
save(input_get_name+": "+input_get_add+": "+input_get_comment)

I try to create a GUI in python to read a file and write a new file but the syntax error shows up

In this program, I try to read a g.code file to generate a new text file.
Firstly, I browse a gcode file from where I want. I, then, browse a folder I want to save. Finally, I run and write some codes and save them as a text file.
I have a problem with function run. When I click run, the SyntaxError shows up.
However, this is only some part of my codes.
from tkinter import *
import os
global file_path
global folder_path
import math
i = 0
fenster = Tk()
fenster.title("Gcode Reader")
fenster.geometry("600x400")
def open_file():
file_path = ''
filename = filedialog.askopenfilename()
file_path = filename
entry.delete(0, END)
entry.insert(0, file_path)
filename.close()
mf = Frame(fenster)
mf.pack()
f1 = Frame(mf, width=100, height=50)
f1.pack(fill=X)
file_path = StringVar
Label(f1,text="Select Your File").grid(row=0, column=0, sticky='e')
entry = Entry(f1, width=50, textvariable=file_path)
entry.grid(row=0,column=1,padx=2,pady=2,sticky='we',columnspan=25)
Button(f1, text="Browse", command=open_file).grid(row=0, column=27, sticky='ew', padx=8, pady=4)
def run():
out_file = open(os.path.join(folder_path, entry2.get()+".txt")
with open(file_path) as in_file :
for line in file_path :
if 'G1 X' in line[0:10] and i==0 :
i=i+1
a=line.find('Y',0,13)
b=line.find('X',0,10)
c=a-1
d=line.find(' ',a,a+10)
x1=float(line[b+1:c])
y1=float(line[a+1:d])
mainloop()
Could it be a typo? You're missing a bracket in this line:
def run():
out_file = open(os.path.join(folder_path, entry2.get()+".txt")
^
That's why you're getting the mentioned error:
with open(file_path) as in_file:
^
SyntaxError: invalid syntax
Just change the line to:
out_file = open(os.path.join(folder_path, entry2.get()+".txt"))

Pass directory name to askopenfilename

I have three functions; with dirBut the user selects a directory the output of which goes into dirname and updates an Entry box. In the third function, dataInput, the user selects a file. I would like the open file dialog to open in the directory previously selected by the user and defined by dirname, however, I'm not sure how to pass dirname to a handle so I can use it in askopenfilename since askdirectory is called from a button.
def UserFileInput(self,status,name):
row = self.row
optionLabel = tk.Label(self)
optionLabel.grid(row=row, column=0, sticky='w')
optionLabel["text"] = name
text = status
var = tk.StringVar(root)
var.set(text)
w = tk.Entry(self, textvariable= var)
w.grid(row=row, column=1, sticky='ew')
self.row += 1
return w, var
def askdirectory(self):
dirname = tkFileDialog.askdirectory()
if dirname:
self.directoryEntry.delete(0, tk.END)
self.directoryEntry.insert(0, dirname)
def askfilename(self):
filename = tkFileDialog.askopenfilename(initialdir=dirname)
if filename:
self.dataInput.delete(0, tk.END)
self.dataInput.insert(0, filename)
currentDirectory = os.getcwd()
directory,var = self.UserFileInput(currentDirectory, "Directory")
self.directoryEntry = directory
dirBut = tk.Button(self, text='Select directory...', command = self.askdirectory)
dirBut.grid(row=self.row-1, column=2)
dataInput, var = self.UserFileInput("", "Data input")
self.dataInput = dataInput
fileBut = tk.Button(self, text='Select input file...', command = self.askfilename)
fileBut.grid(row=self.row-1, column=2)
Assuming askdirectory and askfilename belong to the same class, try assigning the directory to self.dirname instead of dirname. Then the variable will be visible anywhere within the class.
def askdirectory(self):
self.dirname = tkFileDialog.askdirectory()
if self.dirname:
self.directoryEntry.delete(0, tk.END)
self.directoryEntry.insert(0, self.dirname)
def askfilename(self):
filename = tkFileDialog.askopenfilename(initialdir=self.dirname)
if filename:
self.dataInput.delete(0, tk.END)
self.dataInput.insert(0, filename)

Categories