tkinter - 询问用户文件目录并运行脚本
我刚开始学Python,遇到了一些问题,真心希望能得到帮助。我到处找资料,但就是找不到答案。
我写了一个脚本,用来比较两个Excel文件中的数据,并把结果写到一个新文件里。这个脚本比较长,里面有很多函数和对象。
现在我想让这个脚本对我工作团队的其他人也有用,所以想做一个图形界面(GUI)。我正在使用Tkinter。我已经创建了两个按钮,让用户选择文件的目录,并把这些目录存储在一个列表里。
我希望我的原始脚本能使用这两个输入,并在点击第三个按钮时运行。
我该如何把我的脚本放进Tkinter应用程序里呢?这是我的应用程序:
from Tkinter import *
import Tkinter, Tkconstants, tkFileDialog
listfile = []
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
button = Tkinter.Button(self,text=u"data 1",command=self.OnButtonClick)
button2 = Tkinter.Button(self,text=u"data 2",command=self.OnButtonClick)
#here is the third button to run the script, the command isn't right
button3 = Tkinter.Button(self,text=u"Run script",command=self.OnButtonClick)
button.pack(side='bottom',padx=15,pady=15)
button2.pack(side='bottom',padx=15,pady=15)
button3.pack(side='bottom',padx=15,pady=15)
def OnButtonClick(self):
x = tkFileDialog.askopenfilename(title='Please select data directory')
listfile.append(x)
# def OnButtonClick2(self):
# Can I run my original script here?
# I read one should not include a function into a function
if __name__ == "__main__":
app = simpleapp_tk(None)
app.title('my application')
app.mainloop()
3 个回答
如果你只是想让用户选择两个文件夹,然后让脚本运行的话,使用图形界面可能有点多余。为了让事情变得简单,我建议去掉界面,让你的脚本做以下几件事:
- 让用户选择第一个文件夹
- 让用户选择第二个文件夹
- 在选择完第一个和第二个文件夹后,自动运行脚本
你可以使用 tkFileDialog.askdirectory() 来实现这个功能,正如 patthoyts 提到的。下面是一个简化的版本:
import tkFileDialog
def your_script(dir1, dir2):
*your script goes here with dir1 and dir2 as inputs for processing*
dir1 = tkFileDialog.askdirectory()
dir2 = tkFileDialog.askdirectory()
your_script(dir1,dir2)
如果你想让最终用户使用起来更方便,可以考虑把你的脚本转换成一个应用程序(如果他们用的是 Mac)或者 exe 文件(如果他们用的是 Windows)。py2app 或 py2exe 可以帮你做到这一点。Mac 系统自带 Python,而 Windows 系统则没有,所以如果你的团队在 Windows 上,没有 Python 的话,他们就无法运行你的脚本。py2whatever 模块可以生成一个包含 Python 的可执行文件,这样即使用户的电脑上没有安装 Python,也能运行你的脚本。
Tk有一个功能叫做 tk_chooseDirectory
,它可以在Windows和MacOSX上打开一个系统自带的文件夹选择器,其他系统则会弹出一个合适的对话框。在Tkinter中,这个功能是通过 filedialog 这个命名空间来使用的,比如:
from tkinter import filedialog
filedialog.askdirectory()
你可以查看 TkDocs 上的一些例子(搜索chooseDirectory)。
如果你问的是如何在解释器中执行Python脚本,这个问题已经在 如何在Python解释器中执行文件? 中讨论过,关于Python3的补充内容可以在 Python 3.0中execfile的替代方法是什么? 找到。
假设你的原始脚本叫做 excel_report.py
,并且它和你的 Tkinter 脚本在同一个文件夹里。我假设 excel_report.py
的结构是合理的,也就是说所有的处理都是在函数里面完成的,并且它有一个 main()
函数,这个函数会从命令行获取文件名,然后调用实际执行工作的函数,
比如 make_report(excelfilename1, excelfilename2, reportname)
。
我还假设 excel_report.py
的结尾是
if __name__ == "__main__":
main()
如果以上这些都成立,那么在你的 Tkinter 脚本里,你只需要在脚本的顶部放入
from excel_report import make_report
然后在你第三个按钮的回调函数里调用 make_report()
,例如
def OnButtonClick3(self):
make_report(self.name1, self.name2, self.reportname)
这里的 self.name1
、self.name2
和 self.reportname
是你通过 Tkinter 文件对话框获取的文件名。