python - 如何使用 tkinter GUI 在 python 中选择函数参数和文件输出路径?
问题描述
我目前有一个 python 文件,我必须每天为不同的 excel 文件运行该文件。
步骤是:
- 打开 .py 文件
- 更改excel文件的目录
- 运行python文件
- 写入 .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()
这会产生:
所以我想要做的是为开始按钮分配一个功能,我可以使用 command=function 轻松完成。
我正在努力做的是:
给定用户的输入,获取该输入并将文件路径用作函数参数。
能够选择一个输出目标(目前我只能选择一个文件而不是目标),然后在我的函数结束时使用该目标路径来编写我的新 excel 文件。
感谢任何输入!
解决方案
将一个函数连接到您的“开始”按钮,该按钮将获取您的条目内容并运行
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
函数中。如果您使用
filedialog.askdirectory()
instead offiledialog.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'
推荐阅读
- javascript - 将 3 个不同的真实陈述连接到 IF ELSE
- apache-spark - 使用 spark-on-k8s 时如何将环境变量注入驱动程序吊舱?
- python - 创建包含变量名作为字符串加值的 txt 文件
- python - 为什么我会收到“错误 1049 (42000):未知数据库”?
- f# - 在 F# 中遍历列表直到满足某些条件
- python - IndexError:列表索引超出范围 - RPi + 步进电机
- node.js - 为什么当我使用“require”时我的变量未定义?
- html - HTML 表格没有响应溢出=滚动或任何高度变化
- ruby - Ruby - Intelli J 在我尝试执行并行测试时抛出“命令行太长。黄瓜失败”
- angular - 是否允许在没有路由器插座的情况下使用子路由?(主要组件内的标签内容)