how to use the text of a Entry in Tkinter - python

I need the text of an entry that I want to output with print()
the Entry is e_out
from tkinter import * from tkinter import filedialog import os def resample():
e_out = StringVar()
os.system('ffmpeg -i "'+ filename + '.mp4" -vf "tblend=all_mode=average,framestep=2,tblend=all_mode=average,framestep=2"
-r 60 '+ e_out + '.mp4')
os.system("cls")
def file_browser():
global e_out
global filename
global resample
root1 = Tk()
root1.geometry("600x400")
e_out = Entry(root1).pack()
filename = filedialog.askopenfilename(initialdir="/Videos", title="Select A File", filetypes=(("videos", "*.mp4"),("all files", "*.*")))
print(filename)
b1 = Button(root1, text="resample", command=resample).pack()
root1.mainloop()
global root root = Tk()
root.geometry("800x500")
root.title("intler")
choose = Button(root, text="choose a file", command=file_browser).pack()
root.mainloop()

you can get the text in an entry box by using the line:
e_out.get()
this will return a string with text in the entry box

Related

How to upload file in python Tkinter to current directory?

I am making a GUI in python with Tkinter. I can browse a file, print the path for it, but how is it possible to save the browsed file into a specific folder (for example the current folder /home/pi/Desktop/gui). Also I want to add the path for the saved file into the database.
def open():
global my_image
window.filename= filedialog.askopenfilename(initialdir="/home/pi/Desktop/gui", title="Select a file", filetypes=(("jpg files", "*jpg"),("all files", "*.*")))
my_label = Label(window, text=window.filename)
my_label.place(x=260,y=140)
print(os.path.basename(window.filename))
complete_name = os.path.join(save_path, os.path.basename(window.filename))
print(complete_name)
def savedata():
conn=sqlite3.connect('database.db')
c=conn.cursor()
c.execute('INSERT INTO users(name,password,audiofile) VALUES (?,?)',(name_entry.get(),name_entry2.get()))
conn.commit()
print("saved")
Here is the full code what I have already:
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from PIL import ImageTk, Image
import sqlite3
import os
import os.path
window = Tk()
window.title("GUI")
label = Label(window, text="GUI", font=('arial',20,'bold'),bg="black",fg="white")
label.pack(side=TOP,fill=X)
label = Label(window,text="",font=('arial',15,'bold'),bg="black",fg="white")
label.pack(side=BOTTOM,fill=X)
save_path = "/home/pi/Desktop/proba/"
def open():
global my_image
window.filename = filedialog.askopenfilename(initialdir="/home/pi/Desktop/gui", title="Select a file", filetypes=(("jpg files", "*jpg"),("all files", "*.*")))
my_label = Label(window, text=window.filename)
my_label.place(x=260,y=140)
print(os.path.basename(window.filename))
complete_name = os.path.join(save_path, os.path.basename(window.filename))
print(complete_name)
def create():
conn=sqlite3.connect('database.db')
c=conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS users(id integer primary key autoincrement, name TEXT, password TEXT, audiofile TEXT, sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL)")
conn.commit()
conn.close()
create()
label = Label(window,text="Name",font=('arial',13,'bold'))
label.place(x=30,y=60)
name_entry=StringVar()
name_entry=ttk.Entry(window, textvariable=name_entry)
name_entry.place(x=170,y=60)
name_entry.focus()
label = Label(window,text="Password",font=('arial',13,'bold'))
label.place(x=30,y=100)
name_entry2=StringVar()
name_entry2=ttk.Entry(window, textvariable=name_entry2)
name_entry2.place(x=170,y=100)
label = Label(window,text="File upload:",font=('arial',13,'bold'))
label.place(x=30,y=140)
def savedata():
conn=sqlite3.connect('database.db')
c=conn.cursor()
c.execute('INSERT INTO users(name,password,audiofile) VALUES (?,?)',(name_entry.get(),name_entry2.get()))
conn.commit()
print("saved")
btn = ttk.Button(window,text='Save Data', command=savedata)
btn.place(x=170,y=220, width=125, height=30)
my_btn = ttk.Button(window, text="Open file", command=open)
my_btn.place(x=170,y=140, width=80, height=25)
window.geometry('640x350')
window.resizable(False,False)
window.mainloop()

button change its text to the file name

How do I force the button to change its text to the filename? Everything works fine, a dialog box opens and files open too. But I still can't change the button name to the file name and save it.
Here is the code:
import tkinter.filedialog as tfd
import tkinter as tk
import os
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
os.startfile(file_name) #open file
btn1 = tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)
You can set the buttons text property using.
button['text'] = fileName
You can also read the button text propeerty to make sure it has been set to the file name in code, I.e. with an if statement.
bText = button['text']
Try using .config -
import tkinter.filedialog as tfd
import tkinter as tk
import os
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
btn1.config(text=file_name) # Configure the button's text
os.startfile(file_name) #open file
btn1 = tk.Button(window, text=f"Open {file_name}", command=open) #button
btn1.place(x = 20, y = 25)
But if you run this code, the button name gets changed to the complete pathname (e.g. - C:/.../Choosen.file), so if you want only the file name ('Choosen.file') then use this -
btn1.config(text=file_name.split('/')[-1])
You can use:
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def open():
global file_name
file_name = tfd.askopenfilename()
btn1["text"] += " '" + file_name + "'"
os.startfile(file_name)
btn1 = tk.Button(window, text="Open file", command=open) # button
btn1.place(x=20, y=25)
tk.mainloop()
This uses the old text of the button and appends '{file_path}' to it -> Open file '{file_path}'
You could define a new class that maintains state. This way you can avoid the global, and will be able to make multiple buttons each with their own files.
class FileButton(tk.Button):
def __init__(self, window, file_name=""):
super().__init__(window, command=self.open)
self.set_text(file_name)
def set_text(self, file_name):
self.file_name = file_name
self["text"] = f"Open {self.file_name}"
def open(self):
if self.file_name == "":
self.set_text(tfd.askopenfilename())
os.startfile(self.file_name)
window = tk.Tk()
window.title("Op")
window.geometry("600x400")
window.resizable(False, False)
btn1 = FileButton(window)
btn1.place(x=20, y=25)
window.mainloop()

Open file and get file path

I'm trying to create a button to browse file and copy that file to a Master file and my code as below:
from tkinter import *
from tkinter import filedialog
def get_file_path():
global file_path
file_path= filedialog.askopenfilename(title = "Select A File", filetypes = (("xlsx", "*.xlsx"), ("xls", "*.xls"), ("xlsm", "*.xlsm"), ("All Files", "*.*")))
l1 = Label(window, text = file_path).pack()
window = Tk()
b1 = Button(window, text = "Open File", command = get_file_path).pack()
window.mainloop()
def close_window():
window.destroy()
print(file_path)
import openpyxl as xl
path1 = ("r'" and file_path)
path2 = (r'C:\Users\...\Write_Data.xlsx')
wb1 = xl.load_workbook(filename=path1)
ws1 = wb1["BASEL_LN_CTR"]
wb2 = xl.load_workbook(filename=path2)
ws2 = wb2["Loan Data"]
for row in ws1:
for cell in row:
ws2[cell.coordinate].value = cell.value
wb2.save(path2)
Everything is working well for me but I have to close window manually to print file_path. I would like to know that there is any way to close window aucomatically. I used destroy() but it not worked.
You created close_window() but you never use it.
You could create another button to run it (or to run directly window.destroy)
window = tk.Tk()
b1 = tk.Button(window, text="Open File", command=get_file_path).pack()
b2 = tk.Button(window, text="Close", comman=window.destroy).pack()
window.mainloop()
Or you should run it directly in get_file_path()
def get_file_path():
global file_path
file_path = filedialog.askopenfilename(title="Select A File", filetypes = (("xlsx", "*.xlsx"), ("xls", "*.xls"), ("xlsm", "*.xlsm"), ("All Files", "*.*")))
if file_path: # empty when pressed `Cancel`
#tk.Label(window, text=file_path).pack()
window.destroy()

How to get value from command tkinter

This is probably a newbie question but I'm having issues figuring out how to get a value from a function, to be used as input in another.
I would also like to have some tips about code organization.
In this example I'm trying to get the filePath and outPut Folder path to be used in the function processFile.
Thank you
Code:
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
version = "v0.0.01"
root = Tk()
def window (main):
main.title("File Opener " + version)
width = main.winfo_width()
main.geometry('500x200')
numero = str(1)
def OpenFile():
fileName = askopenfilename(initialdir="C:/",
filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
title = "Select PDF File",
)
labelName = Label(text="File Path: " + fileName)
labelName.pack()
print(fileName)
return fileName
def outputFolder(): #Bug, label keeps adding paths
outPath = askdirectory()
labelName2 = Label(text="Output Folder: " + outPath)
labelName2.pack()
print(outPath)
return outPath
def processFile(inFile,outFolder):
''' print(fileName) get input name and output variables
print(outPath)'''
label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()
#Button Open-----------
button1 = Button (text = "Open File", command = OpenFile)
button1.pack()
#Button Start---------
buttonStart = Button (text = "Start Process", command = processFile)#give as parameter inputFile and link
buttonStart.place(height=50, width=100)
#Button Open-----------
button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()
#Menu Bar ----------------
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
window(root)
root.mainloop()
If you use the function in a variable the returned result from the function is stored in the variable.
def Function1(x):
return x*2
var1 = Function1(5)
Then var1 = 10.
But about your buttons, do you want to take input from the user that will be saved when the button is pressed or do you want the button to send a set value?
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
version = "v0.0.01"
root = Tk()
def window (main):
main.title("File Opener " + version)
width = main.winfo_width()
main.geometry('500x200')
main.configure(background = 'black')
numero = str(1)
#openFile
def OpenFile():
global fileName
fileName = askopenfilename(initialdir="C:/",
filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
title = "Select PDF File",
)
labelName = Label(text="File Path: " + fileName)
labelName.pack()
print(fileName)
return str(fileName)
#getOutputPath
def outputFolder(): #Bug, label keeps adding paths
outPath = askdirectory()
labelName2 = Label(text="Output Folder: " + outPath)
labelName2.pack()
print(outPath)
return outPath
#testFunct
def printFilename(inArg):
print(inArg)
x = OpenFile()
print (OpenFile())
lambda: printFilename(fileName)
#processRealDeal
def processFile(): #THIS IS THE MAIN FUNC
''' print(fileName) get input name and output variables
print(outPath)'''
print (OpenFile)
label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()
#Button Open-----------
button1 = Button (text = "Open File", command = OpenFile)
button1.pack()
#Button Start---------
buttonStart = Button (text = "Start Process", command = lambda: printFilename("Hello World!!!"))#give as parameter inputFile and link
buttonStart.place(height=50, width=100)
#Button Open-----------
button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()
#Menu Bar ----------------
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
window(root)
root.mainloop()
I cant see that you have declared the global fileName variabel outside the function.
I did this
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askdirectory
import PyPDF2
from PyPDF2 import PdfFileWriter, PdfFileReader
version = "v0.0.01"
root = Tk()
fileName = "test"
def window (main):
main.title("File Opener " + version)
width = main.winfo_width()
main.geometry('500x200')
main.configure(background = 'black')
numero = str(1)
#openFile
def OpenFile():
global fileName
fileName = askopenfilename(initialdir="C:/",
filetypes =(("PDF File", "*.pdf"),("All Files","*.*")),
title = "Select PDF File",
)
labelName = Label(text="File Path: " + fileName)
labelName.pack()
test()
return str(fileName)
#getOutputPath
def test():
print(fileName)
def outputFolder(): #Bug, label keeps adding paths
outPath = askdirectory()
labelName2 = Label(text="Output Folder: " + outPath)
labelName2.pack()
print(outPath)
return outPath
#testFunct
def printFilename(inArg):
print(inArg)
x = OpenFile()
print (OpenFile())
lambda: printFilename(fileName)
#processRealDeal
def processFile(): #THIS IS THE MAIN FUNC
''' print(fileName) get input name and output variables
print(outPath)'''
print (OpenFile)
label = ttk.Label(root, text ="",foreground="black",font=("Helvetica", 16))
label.pack()
#Button Open-----------
button1 = Button (text = "Open File", command = OpenFile)
button1.pack()
#Button Start---------
buttonStart = Button (text = "Start Process", command = lambda: printFilename("Hello World!!!"))#give as parameter inputFile and link
buttonStart.place(height=50, width=100)
#Button Open-----------
button3 = Button (text = "Output Folder", command = outputFolder)
button3.pack()
#Menu Bar ----------------
menu = Menu(root)
root.config(menu=menu)
file = Menu(menu)
file.add_command(label = 'Open', command = OpenFile)
file.add_command(label = 'Exit', command = lambda:exit())
menu.add_cascade(label = 'File', menu = file)
window(root)
root.mainloop()
And the test function prints the chosen file. So the global variable is now containing the correct value.
So just declare it at the top and you will be able to retrieve the value

How can I use the output from tkFileDialog.askdirectory to fill a tkinter Entry box

I have a tkinter Entry box in which the user can insert a path to the directory. Alternatively the user can click a button to select the directory. How can I set the output from the button to fill the Entry box? I have tried the following but dirname is not a global variable and so is not recognised by UserFileInput. Also how can I bind the button next to the entry field.
from Tkinter import *
import tkFileDialog
def askdirectory():
dirname = tkFileDialog.askdirectory()
return dirname
def UserFileInput(status,name):
optionFrame = Frame(root)
optionLabel = Label(optionFrame)
optionLabel["text"] = name
optionLabel.pack(side=LEFT)
text = str(dirname) if dirname else status
var = StringVar(root)
var.set(text)
w = Entry(optionFrame, textvariable= var)
w.pack(side = LEFT)
optionFrame.pack()
return w
if __name__ == '__main__':
root = Tk()
dirBut = Button(root, text='askdirectory', command = askdirectory)
dirBut.pack(side = RIGHT)
directory = UserFileInput("", "Directory")
root.mainloop()
Your UserFileInput should return var, not w. Then you can use var.set(dirname) in your askdirectory function which doesn't have to return anything.
I'm not sure however what you try to achieve with text = str(dirname) if dirname else status. Why not just use text = status since dirname can't yet be defined there?
Edit:
This should work the way you want it to. The 'print entry text' button shows that you can retreive whatever is in the entry box, either written by the user or put there by the code.
from Tkinter import *
import tkFileDialog
def askdirectory():
dirname = tkFileDialog.askdirectory()
if dirname:
var.set(dirname)
def UserFileInput(status,name):
optionFrame = Frame(root)
optionLabel = Label(optionFrame)
optionLabel["text"] = name
optionLabel.pack(side=LEFT)
text = status
var = StringVar(root)
var.set(text)
w = Entry(optionFrame, textvariable= var)
w.pack(side = LEFT)
optionFrame.pack()
return w, var
def Print_entry():
print var.get()
if __name__ == '__main__':
root = Tk()
dirBut = Button(root, text='askdirectory', command = askdirectory)
dirBut.pack(side = RIGHT)
getBut = Button(root, text='print entry text', command = Print_entry)
getBut.pack(side = BOTTOM)
w, var = UserFileInput("", "Directory")
root.mainloop()

Categories