0

This may be tricky but I'll try to put it clear. i have created two buttons, 1st button search folder and select individual filename as input, 2nd button select folder and take its directory as input and read all its files inside.

I want to create 3rd button(Execute) where it should know which button i selected and based on that it needs to do execute function.

Now,

import cx_oracle
conn = cx_oracle.connect()

from tkinter import*
from tinter import filedialog as fd
import pandas as pd
from tkinter import messagebox
from tkinter.messagebox import showinfo

window=Tk()
window.withdraw
window.title("ETL Automation")
winow.geometry("400x250+10+10")
window['bacground']='#34495E'

cursor = conn.cursor
global filename

def select_folder()
    folder_selected = filedialog.askdirectory()
    
def select_individual_file()
    filetypes = (
        'text files','*sql'),
        ('All files', '*.*')
    )
    global filename
    filename = fd.askopenfilename(title= ' ',
        initiadir=r'C:\Users\Documents',
        filetypes=filetypes)

#Now i wrote this for to execute 1 sql file         
def execute_query
    with open(filename) as inserts:
        query = inserts.read()
    cursor.execute(query)
    global row
    row = cursor.fetchall()
    messagebox.showinfo('Alert',"Query executed")
    

#This code to execute the sql files inside the folder_selected
cd = (folder_selected)

for root, dirnames, filenames in os.walk(folder_selected)
    for filenamess in fnmatch.filter(filnames, '*sql'):
    with open (cd+'\\'+filenamess) as inserts:
    queries = inserts.read()
    cursor.execute(queries)
    rows = cursor.fetchall()
    
    
btn = Button(window, text="Select in Batch", fg = 'black',command=folder_selected,font="10")
btn = Button(window, text="Select single file", fg = 'black',command=select_individual_file,font="10")
btn = Button(window, text="Execute", fg = 'black',command=execute_query,font="10")

btn.place(x=40, y=80)
btn1.place(x=40,y=80)
btn1.place(x=40,y=80)
window.mainloop    

My intention is to keep the same button to execute button for both the folder_selected and select_individual_file, but the execute button have to identify which input to take by writing the condition or something. Please help.

4
  • If i understand you correctly, simply define a variable outside of your functions, overwrite the value of that variable afer executing either select_folder() or select_individual_file(), query that variable in the execute_query() function and decide what to do with if. I am utterly confused about your question tbh. Also, the code you provided is full of errors. Commented Mar 4, 2022 at 11:48
  • I have have two button select_folder() which takes file directory as input and select_individual_file() the select one single file as input. now I have execute button but I don't know how to tell the execute button to take which I have selected for input. Is it folder or single file. Sorry for the code it's working but I may have missed some parts.... Commented Mar 4, 2022 at 11:54
  • There is two codes for execute here..one for selected_folder (it will execute every sql files inside that folder) and select_individual_file(it will execute single file). Since I giving here one button I don't know how to say in code take the folder as input or single file as input. Commented Mar 4, 2022 at 11:59
  • buttons 1 and 2 you should keep data in global variable(s) and 3th button should run function which get data from this global variable(s). Commented Mar 4, 2022 at 12:45

2 Answers 2

1

You can simply use single global variable and use os.path.isdir() and os.path.isfile() to check whether a folder or a file is selected:

...
import os
from tkinter import filedialog as fd
...

selected_path = '' # initialise the global variable

def select_folder():
    global selected_path
    selected_path = fd.askdirectory()

def select_individual_file():
    global selected_path
    filetypes = (
        ('SQL files', '*.sql'),
        ('All files', '*.*'),
    )
    selected_path = fd.askopenfilename(initialdir='C:/Users/Documents', filetypes=filetypes)

def execute_query():
    if os.path.isdir(selected_path):
        print('Folder selected:', selected_path)
    elif os.path.isfile(selected_path):
        print('File selected:', selected_path)
    else:
        print('No item selected')

...
Sign up to request clarification or add additional context in comments.

Comments

1

A couple of points why your code can not work:

  • you overwrite your button each time you write btn=..
  • your functions miss a couple of : after function definitions
  • you call a couple of functions improperly, missing ()
  • im pretty sure there is no window attribute bacground
  • you forgot closing one of your strings

Then, to the actual problem:

You have to store the results of your functions in some way. Easiest is to have a tuple, where the first part stores your method, and the second the actual data. Then you can simply query what is stored in that tuple in your execute function. In general i would advise against the use of global and would suggest to work with classes instead, but i think for now this solution is most understandable to you:

from tkinter import *
from tkinter import filedialog as fd
window = Tk()

# this is where you store which function you used as well as the selection-data
selection = (None, None)

def select_folder():
    global selection
    selected_folder = fd.askdirectory()
    # the if prevents overwriting the variable when pressing cancel
    if selected_folder:
        # here you overwrite your variable after running the function
        selection = ("folder", selected_folder)

def select_individual_file():
    global selection
    filetypes = (("SQL files", "*.sql"),
        ("All files", "*.*"))
    filename = fd.askopenfilename(filetypes=filetypes)
    # the if prevents overwriting the variable when pressing cancel
    if filename:
        # here you overwrite your variable after running the function
        selection = ("file", filename)

def execute_query():
    # here you check the value of selection and decide what to do
    # selection[0] stores None, "file" or "folder", selection[1] your files etc.
    if selection[0] == None:
        print("No files selected")
        return

    if selection[0] == "folder":
        print("You selected a folder:", selection[1])
        print("Here goes the code you want to execute for a folder..")

    if selection[0] == "file":
        print("You selected a file:", selection[1])
        print("Here goes the code you want to execute for a file..")

# i used pack instead of place and didnt store the objects in variables, because i am lazy
Button(window, text="Select folder", command=select_folder).pack()
Button(window, text="Select files", command=select_individual_file).pack()
Button(window, text="Execute qry", command=execute_query).pack()

window.mainloop()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.