首页 > 解决方案 > 如何使用 tkinter GUI 在 python 中选择函数参数和文件输出路径?

问题描述

我目前有一个 python 文件,我必须每天为不同的 excel 文件运行该文件。

步骤是:

  1. 打开 .py 文件
  2. 更改excel文件的目录
  3. 运行python文件
  4. 写入 .xlsx

这需要一个 excel 文件,因为 pandas 数据框会进行一些操作和其他事情,并吐出一个 excel 文件。

问题是我每次都必须在代码中手动更改目录。

我宁愿为我构建一个漂亮的 GUI 来选择我想要操作的源文件,选择输出目录,然后单击开始启动 .py 脚本。

我当前的 .py 文件不是作为函数编写的,但它只是一些数据的一系列步骤,因此我可以轻松地将其编写为函数,如下所示:

def data_automation(my_excel_file):
    #do some stuff
    pd.to_excel(output directory)

我目前有这个:

import tkinter.filedialog as filedialog
import tkinter as tk

master = tk.Tk()

def input():
    input_path = tk.filedialog.askopenfilename()
    input_entry.delete(1, tk.END)  # Remove current text in entry
    input_entry.insert(0, input_path)  # Insert the 'path'


def output():
    path = tk.filedialog.askopenfilename()
    input_entry.delete(1, tk.END)  # Remove current text in entry
    input_entry.insert(0, path)  # Insert the 'path'


top_frame = tk.Frame(master)
bottom_frame = tk.Frame(master)
line = tk.Frame(master, height=1, width=400, bg="grey80", relief='groove')

input_path = tk.Label(top_frame, text="Input File Path:")
input_entry = tk.Entry(top_frame, text="", width=40)
browse1 = tk.Button(top_frame, text="Browse", command=input)

output_path = tk.Label(bottom_frame, text="Output File Path:")
output_entry = tk.Entry(bottom_frame, text="", width=40)
browse2 = tk.Button(bottom_frame, text="Browse", command=output)

begin_button = tk.Button(bottom_frame, text='Begin!')

top_frame.pack(side=tk.TOP)
line.pack(pady=10)
bottom_frame.pack(side=tk.BOTTOM)

input_path.pack(pady=5)
input_entry.pack(pady=5)
browse1.pack(pady=5)

output_path.pack(pady=5)
output_entry.pack(pady=5)
browse2.pack(pady=5)

begin_button.pack(pady=20, fill=tk.X)


master.mainloop()

这会产生:

tk_output

所以我想要做的是为开始按钮分配一个功能,我可以使用 command=function 轻松完成。

我正在努力做的是:

  1. 给定用户的输入,获取该输入并将文件路径用作函数参数。

  2. 能够选择一个输出目标(目前我只能选择一个文件而不是目标),然后在我的函数结束时使用该目标路径来编写我的新 excel 文件。

感谢任何输入!

标签: pythonpython-3.xuser-interfacetkinter

解决方案


  1. 将一个函数连接到您的“开始”按钮,该按钮将获取您的条目内容并运行data_automation()。就像是

    def begin():
        my_excel_file = input_entry.get()
        output_directory = output_entry.get()
        data_automation(my_excel_file, output_directory)
    

    我已将output_directory参数添加到您的data_automation函数中。

  2. 如果您使用filedialog.askdirectory()instead of filedialog.askopenfilename(),您将能够选择目录而不是文件。顺便说一句output(),我想你想插入结果output_entry,而不是input_entry

    def output():
        path = tk.filedialog.askdirectory()
        output_entry.delete(1, tk.END)  # Remove current text in entry
        output_entry.insert(0, path)  # Insert the 'path'
    

推荐阅读