使用GUI python浏览要打开和运行的文件

2024-03-28 21:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有一些python脚本。我需要用几个按钮创建一个GUI,通过浏览打开那些文件。我必须通过单击GUI按钮来运行这些脚本,并将输出写入一个n excel表。我试过下面的代码,但用它我可以读取文件!请帮忙? 谢谢你

from Tkinter import *            
from tkFileDialog   
import askopenfilename      

def callback():
    r = open(askopenfilename(),'r')

a = Button(text='click me', command=callback)
a.pack()

mainloop()

Tags: 文件代码fromimport脚本tkinterdefcallback
3条回答
        import Tkinter, tkFileDialog
        root = Tkinter.Tk()
        root.withdraw()
        dirname=tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
        do something with dirname
        print dirname

#This code for file selection:

    from Tkinter import Tk
    from tkFileDialog import askopenfilename

    Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing

    filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
    print(filename)

下面的代码是一个简单的示例,它从选定的输入文件中读取每一行,然后将其写入名为output.xls的新excel文件。它使用优秀的xlwt library创建excel文件。您还可以选择使用csv模块创建csv文件,该模块是python标准库的一部分,excel也可以读取该库。使用xlwt的优点是,您可以应用格式化、合并单元格、公式以及作为xls文件格式一部分的许多其他功能。

import xlwt
from Tkinter import *            
from tkFileDialog   import askopenfilename      

def callback():
    filename = askopenfilename()
    wb = xlwt.Workbook()
    ws0 = wb.add_sheet('Sheet1')
    with open(filename, 'r') as f:
        for i, line in enumerate(f):
            ws0.write(i, 0, line.strip())
    wb.save('output.xls')

errmsg = 'Error!'
a = Button(text='click me', command=callback)
a.pack()
mainloop()

在callback()中,不要打开文件,而是使用execfile(“abc.py”)执行文件

def callback():
    abc = askopenfilename()
    execfile("abc.py")

相关问题 更多 >