如何从选定的按钮 tkinter python 使用 input/command

How to use input/command from selected button tkinter python

这可能有点棘手,但我会尽量把它说清楚。我创建了两个按钮,第一个按钮搜索文件夹和 select 单个文件名作为输入,第二个按钮 select 文件夹并将其目录作为输入并读取其中的所有文件。

我想创建第三个按钮(执行),它应该知道我 select 编辑了哪个按钮,并基于它需要执行功能。

现在,

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    

我的意图是让 folder_selected 和 select_individual_file 都使用相同的按钮来执行按钮,但是执行按钮 必须通过编写 if 条件或其他内容来确定要采用的输入。请帮忙。

您的代码无法运行的几点原因:

  • 你每次写 btn=..
  • 都会覆盖你的按钮
  • 你的函数在函数定义后遗漏了几个 :
  • 你调用了几个函数不正确,缺少 ()
  • 我很确定没有 window 属性 bacground
  • 您忘记关闭其中一个字符串

那么,针对实际问题:

您必须以某种方式存储函数的结果。最简单的是有一个元组,其中第一部分存储您的方法,第二部分存储实际数据。然后,您可以简单地在执行函数中查询存储在该元组中的内容。一般来说,我会建议不要使用 global 并建议使用 类,但我认为现在这个解决方案对你来说是最容易理解的:

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

您可以简单地使用单个全局变量并使用 os.path.isdir()os.path.isfile() 来检查是否选择了文件夹或文件:

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

...