How to get value from command tkinter - python

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

Related

how to use the text of a Entry in Tkinter

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

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()

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 restore button

I want to be able to control the default restored size of my windows when click the restore button of the window itself. Right now whenever I click the restore button it stays with the maximized size which is the screen resolution but it just moves to the right a little bit. I want in a way that I can set up a default size before dragging it smaller or bigger depending on the desired size. I attached my code for reference
from tkinter import *
from tkinter.filedialog import *
from pathlib import Path
from win32api import GetSystemMetrics
filename = None
file_path = None
files = [
('All Files', '*.*'),
('Python Files', '*.py'),
('Text Document', '*.txt')
]
def newFile():
global filename
filename = "untitled"
text.delete(0.0, END)
def saveFile():
global filename
t = text.get(0.0, END)
try:
f = open(file_path, mode='w')
f.write(t)
f.close()
except:
saveAs()
def saveAs():
f = asksaveasfile(mode='w', initialdir="C:\\Users\\charl/Documents", filetypes=files, defaultextension=".txt")
t = text.get(0.0, END)
f.write(t)
# except:
# f.showerror(title="Oops!", message="Unable to save file...")
def openFile():
global filename, file_path
f = askopenfile(mode='r')
filename = Path(f.name).stem
file_path = f.name
t = f.read()
text.delete(0.0, END)
text.insert(0.0, t)
f.close()
root = Tk()
root.title("My Python Text Editor")
root.state('zoomed')
root.minsize(width=400, height=400)
root.maxsize(width=GetSystemMetrics(0), height=GetSystemMetrics(1))
text = Text(root, width=400, height=400)
text.pack(fill="both", expand=True)
menubar = Menu(root)
file = Menu(root)
filemenu = Menu(menubar, tearoff=False)
filemenu.add_command(label="New", command=newFile)
filemenu.add_command(label="Open", command=openFile)
filemenu.add_command(label="Save", command=saveFile)
filemenu.add_command(label="Save As...", command=saveAs)
filemenu.add_separator()
filemenu.add_command(label="Quit", command=root.quit())
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
It is because the text box is too large. Try removing the width and height options from text = Text(...) like below:
text = Text(root)

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