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:UsersDocuments', 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.
Advertisement
Answer
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') ...