Using Tkinter and suprocess.call - python-3.x

I would like to use tkinter to open a window that will allow a user to select two separate files that will be manipulated several times within my script. I am having trouble finding a way to set the file that will be selected using the button in my tkinter window as a variable so that it can be used within subprocess.call. I have found invoke() but it doesn't seem to have any affect. Any ideas on what I might do would be greatly appreciated.
import os
import sys
import gdal
from gdalconst import *
import numpy as np
import math
import subprocess
from subprocess import call
import math
import datetime
import shutil
import tkinter
from tkinter import *
from tkinter import filedialog
newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
if not os.path.exists(newpath):
os.makedirs(newpath)
newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
if not os.path.exists(newpath_2):
os.makedirs(newpath_2)
newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
if not os.path.exists(newpath_3):
os.makedirs(newpath_3)
if __name__== '__main__':
# Set all of the necessary constants so that the script can create and save the pertinent files
# on the users desktop
#tk1 = Tk()
#tk2 = Tk()
#callTK = 'src_dataset =' + tk1
#callTK_2 = 'srcVH =' + tk2
gdalTranslate = 'C:\Program Files (x86)\GDAL\gdal_translate.exe'
tk1.fileName = filedialog.askopenfilename(text="Open HV File")
tk2.fileName = filedialog.askopenfilename(text="Open VH File")
dst_dataset = os.path.expanduser('~\\Desktop\\Components\\Float32\\newHV32.img')
dstVH = os.path.expanduser('~\\Desktop\\Components\\Float32\\newVH32.img')
sttime = datetime.datetime.now().strftime('(Time_Run = %Y-%d-%m_%H:%M:%S)')
wheel_install_1 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install.py')
wheel_install_2 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install2.py')
ridofz = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\ridofZsv2.py')
to_dB = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\to_dBv2.py')
db_HV = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newHVdB.img')
db_VH = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newVHdB.img')
cmd = "-ot float32 -of HFA" # hopefully this works
# Install necessary packages, which are GDAL and Numpy
# try:
#os.system(wheel_install_1)
#print ("GDAL intalled")
#os.system(wheel_install_2)
#print ("Numpy installed")
#except:
#print ("The packages are't installing properly")
#sys.exit()
# Create three new folders which will house the files that will be created
# along each sequential step of the script
#newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
#if not os.path.exists(newpath):
#os.makedirs(newpath)
#newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
#if not os.path.exists(newpath_2):
#os.makedirs(newpath_2)
#newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
#if not os.path.exists(newpath_3):
#os.makedirs(newpath_3)
root = Tk()
#root.fileName = filedialog.askopenfilename()
root.title("Utilis Sigma Test")
root.iconbitmap(r"C:\Users\jack.UTILIS\Desktop\images\sigma.ico")
root.configure(background="#179EBB")
topFrame = Frame(root)
topFrame.pack()
photo = PhotoImage(file="C:\\Users\\jack.UTILIS\\Desktop\\images\\Utilis_Branding2015_FINAL_Small.gif")
label = Label(root, image=photo)
label.pack(side=RIGHT)
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(root, text="Open HV File", fg="black", command=filedialog.askopenfilename)
button2 = Button(root, text="Open VH FIle", fg="black", command=filedialog.askopenfilename)
button1.pack(side=LEFT)
button2.pack(side=RIGHT)
hvfullCmd = ' '.join([gdalTranslate, cmd, tk1.fileName,dst_dataset])
subprocess.call(hvfullCmd)
vhfullCmd = ' '.join([gdalTranslate,cmd, tk2.fileName,dstVH])
subprocess.call(vhfullCmd)
root.mainloop()

You have to create own function which get filename from askopenfilename and does something with this file. Then you can assign this file to button using command=
import tkinter as tk
from tkinter import filedialog
# --- functions ---
def on_click():
filename = filedialog.askopenfilename()
if filename:
print("Filename:", filename)
else:
print("Filename: not selected")
# --- main ---
root = tk.Tk()
btn = tk.Button(root, text='Click Me', command=on_click)
btn.pack()
root.mainloop()

Related

TKinter Widget creation... Issue with arrangement of widgets

I was trying to create some nested widgets within file widget however exit is appearing above open. I tried changing the index but still the problems persists any idea how to fix this?
#!/usr/bin/python3
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
import sys
class GuiBaseClass():
def __init__(self,root):
# create widgets
self.root=root
root.title('GUIBASECLASS V0.1')
root.option_add('*tearOff', False)
self.menu=dict()
self.menubar = tk.Menu(root)
#File
menu_file = tk.Menu(self.menubar)
self.menubar.add_cascade(menu=menu_file,label='File',underline=0)
menu_file.add_separator()
menu_file.add_command(label='Exit', command=self.Exit,underline=0)
#Edit
menu_edit = tk.Menu(self.menubar)
self.menubar.add_cascade(menu=menu_edit,label='Edit',underline=0)
#Help
menu_help = tk.Menu(self.menubar)
menu_help.add_command(label='About', command=self.About, underline=0)
self.menubar.add_cascade(menu=menu_help,label ='Help',underline=0)
#config
root.config(menu=self.menubar)
self.menu['menubar'] = self.menubar
self.menu['File'] = menu_file
self.menu['Edit'] = menu_edit
self.menu['Help'] = menu_help
self.frame = ttk.Frame(root)
self.frame.pack(fill='both',expand=True)
# public functions
def mainLoop(self):
self.root.mainloop()
def getFrame(self):
return(self.frame)
def getMenu(self,entry):
if entry in self.menu:
return (self.menu[entry])
else:
# we create a new one
last = self.menu['menubar'].index('end')
self.menu[entry]= tk.Menu(self.menubar)
self.menu['menubar'].insert_cascade(
last, menu=self.menu[entry],label=entry)
return(self.menu[entry])
# private functions
def Exit(self,ask=True):
res = tk.messagebox.askyesno(title='Are you sure',message='Really quit the application')
if res:
sys.exit(0)
pass
def About(self):
print('print GUIBASECLASS V0.1')
if __name__ == '__main__':
root=tk.Tk()
bapp = GuiBaseClass(root)
# example for using the BaseClass in other applications
mnu=bapp.getMenu('Edit')
mnu.add_command(label='Copy',command=lambda: print('Copy'))
# example for using getFrame
frm=bapp.getFrame()
btn=ttk.Button(frm,text="Button X",command=lambda: sys.exit(0))
btn.pack()
bapp.mainLoop()
#!/usr/bin/python3
import tkinter as tk
import tkinter.ttk as ttk
from tkinter import filedialog
from tkinter import messagebox
from GuiBaseClass import GuiBaseClass
import os , sys
class PumlEditor(GuiBaseClass):
def __init__(self, root):
super().__init__(root)
# Create the File menu and add a "Open..." option
mnu_file = self.getMenu('File')
mnu_file.add_command(0, label='Open...', underline=0, command=self.fileOpen)
mnu_file.add_separator()
# Create the main text area
frame = self.getFrame()
#insert tk.Text
self.text = tk.Text(frame, wrap='word', undo=True)
self.text.insert('end', 'Hello start writing, please...')
self.text.delete('1.0','end')
self.text.pack(fill='both', expand=True)
def fileOpen(self, filename=''):
# Open a file dialog to select a file to open
if filename == "":
filename = filedialog.askopenfilename()
if filename != "":
self.text.delete('1.0','end')
file = open(filename,'r')
for line in file:
self.text.insert('end',line)
if __name__ == '__main__':
root = tk.Tk()
root.geometry("300x200")
pedit = PumlEditor(root)
# Create the PumlEditor instance and start the main loop
root.title("PumlEditor 2022")
if len(sys.argv)>1:
if os.path.exits(sys.arg[1]):
pedit.fileOpen(sys.argv[1])
pedit.mainLoop()
Open to appear before exit in files widget

how to break looping in tkinter?

this is my code.
from PyPDF2 import PdfFileReader
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
root = tk.Tk()
label_list = []
def get_info(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
page = pdf.getPage(4)
label_list[0].config(text = "Title")
label_list[1].config(text = info.title)
label_list[2].config(text = "Author")
label_list[3].config(text = info.author)
label_list[4].config(text = "Subject")
label_list[5].config(text = info.subject)
label_list[6].config(text = "Abstract")
label_list[7].config(text = page.extractText())
save = tk.Button(root, text="Save")
save.pack()
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
browsebutton = tk.Button(root, text="Choose a File", command=browsefunc)
browsebutton.pack()
pathlabel = tk.Label(root)
pathlabel.pack()
for i in range(8):
label_list.append(tk.Label(root, text=""))
label_list[i].pack()
root.mainloop()
i added button save which the button will show when i choose the file, and when i choose a new file, i got 2 save buttons and more.
how can i break the data, and when i choose a new file i only have 1 button?
Here is one way you can get the button to show when you need it and then get rid of it when you don't.
We can have a tracking variable to see if we currently have a button open and when we use the button we can get rid of the button as part of the function. So create when we need it and destroy when its done.
from PyPDF2 import PdfFileReader
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
root = tk.Tk()
label_list = []
track_save_button = False
def save_func():
global track_save_button, save
# your code for saving data here
save.destroy()
track_save_button = False
def get_info(path):
global track_save_button, save
if track_save_button == False:
save = tk.Button(root, text="Save", command=save_func)
save.pack()
track_save_button = True
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
page = pdf.getPage(4)
label_list[0].config(text = "Title")
label_list[1].config(text = info.title)
label_list[2].config(text = "Author")
label_list[3].config(text = info.author)
label_list[4].config(text = "Subject")
label_list[5].config(text = info.subject)
label_list[6].config(text = "Abstract")
label_list[7].config(text = page.extractText())
else:
print("Save Button is already active!")
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
browsebutton = tk.Button(root, text="Choose a File", command=browsefunc)
browsebutton.pack()
pathlabel = tk.Label(root)
pathlabel.pack()
for i in range(8):
label_list.append(tk.Label(root, text=""))
label_list[i].pack()
root.mainloop()

Open a file with a button then storing the path in Python3

As the title states, I want to open a file with a browse button then store the file path for later use. I have no issue browsing the file, I just can't get the path to store into a variable. Many thanks.
from tkinter import *
from tkinter import filedialog
import openpyxl
from termcolor import cprint
# initializing tk
root = Tk()
root.title("Tools")
root.geometry("600x300")
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack(side = BOTTOM )
def getFile():
# open dialog box to select file
root.filename = filedialog.askopenfilename(initialdir="/", title="Select file")
#create button
browsebutton = Button(frame, text="Browse", command=getFile)
browsebutton.pack(side = BOTTOM)
#store the open file path into a variable
path = root.filename
You can use global(you should avoid global if possible) or use a class
def getfile():
path.set(filedialog.askopenfilename(initialdir="/", title="Select file")
def do_other_work_with_path():
#your Code here
print(path.get())
path = StringVar()
#using global
def getfile():
global path
path = filedialog.askopenfilename(initialdir="/", title="Select file")
# or using a class for your whole gui
from tkinter import *
from tkinter import filedialog
root = Tk()
class GUI:
def __init__(self, parent):
self.parent=parent
self.button=Button(self.parent, text='Browse', command=self.getfile)
self.button.pack()
def getfile(self):
self.path=filedialog.askopenfilename(initialdir="/", title="Select file")
gui=GUI(root)
#you can also call gui.path with a class
root.mainloop()

Tkinter "Open" Window

I want to replicate the "Open" button (For example on notepad to open a txt file) but I want to have it as a button beside entry in a tkinter window so I could either enter a directory or use button to select a specific folder.
import glob
import os
from tkinter import *
import tkinter.messagebox
for file in os.listdir(r"C:\directory"):
print(file)
root = Tk()
root.resizable(width=FALSE, height=FALSE)
def inital():
pass
#Making Widgets
frameT = Frame(root)
frameT.pack(side=TOP)
frameB = Frame(root)
frameB.pack(side=BOTTOM)
labelstart = Label(frameT, text="Configure")
labelstart.grid()
dirlabel = Label(frameT, text="Directory:")
dirlabel.grid(row=1)
dirinput = Entry(frameT)
dirinput.grid(row=2)
root.mainloop()
How about this :
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
def askopenfile():
# If you want to browse files.
path_to_file = tkFileDialog.askopenfilename() # for a file
# If you want to browse directories.
path_to_folder = tkFileDialog.askdirectory() # for a directory
print "File: " + path_to_file
print "Folder: " + path_to_folder
root = Tk()
b = Button(root, text="CLICK ME", command=askopenfile)
b.pack()
root.mainloop()
Hopefully this will help you, Yahli.

Loading an audio file using file dialog and playing it with pygame

I'm trying to load a file using the tkinter GUI file dialog and then pass this to another function that will play it using pygame (though I'm open to using another package if it's easier), how would I go about doing this? Below is what a code sample that is representative of what I have so far:
import tkinter, pygame
from tkinter import *
from pygame import *
from tkinter import filedialog
root = Tk()
def open_masker():
global fileName
fileName = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"), ("All Files", "*.*")))
masker_track = fileName
if fileName =="":
fileName = None
else:
fh = open(fileName, "r")
fh.close()
def masker_screen():
global m_screen
m_screen = Toplevel(root)
m_screen.geometry('600x600')
m_screen.transient(root)
m_label = Label(m_screen, text = "Playing New Masker Noise")
m_label.pack(anchor = CENTER)
noise = pygame.mixer.Sound(file = fileName)
noise.play(0, 5000)
noise.stop()
b1 = Button(root, text = 'open file',command = open_masker).pack(anchor=CENTER)
b2 = Button(root, text = 'continue', command = masker_screen).pack(anchor = E)
root.mainloop()
Which just returns the error that pygame couldn't load the file. Is this because it's being loaded in as a string into the fileName variable? If so, how do I change that and access the actual file?
Thanks!
Ok, I have fixed some problems you had, and this is my complete working solution (see the comments in the code for explanations):
import pygame
from tkinter import * # not advisable to import everything with *
from tkinter import filedialog
pygame.mixer.init() # initializing the mixer
root = Tk()
audio_file_name = ''
def open_masker():
global audio_file_name
audio_file_name = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"), ("All Files", "*.*")))
def masker_screen():
# we will also use the audio_file_name global variable
global m_screen, audio_file_name
m_screen = Toplevel(root)
m_screen.geometry('600x600')
m_screen.transient(root)
m_label = Label(m_screen, text = "Playing New Masker Noise")
m_label.pack(anchor = CENTER)
if audio_file_name: # play sound if just not an empty string
noise = pygame.mixer.Sound(audio_file_name)
noise.play(0, 5000)
b1 = Button(root, text = 'open file',command = open_masker)
# does not make sense to call pack directly
# and stored the result in a variable, which would be None
b1.pack(anchor=CENTER)
Button(root, text = 'continue', command = masker_screen).pack(anchor = E)
root.mainloop()
See documentation for more information on how to use correctly the mixer module.

Resources