How to use input/command from selected button tkinter python

Question:

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.

Asked By: Devaraj Mani Maran

||

Answers:

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()
Answered By: mnikley

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

...
Answered By: acw1668
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.