Python界面编程

python生成对话框,通过按钮操作,代开系统自带的对话框选择并打开文件。

import tkinter
from tkinter import filedialog
window = tkinter.Tk()
window.title("选择文件")
window.geometry('400x300')

e1 = tkinter.Label(window, text="路径:")#这是标签
e1.grid(row=1,column=0)
g = tkinter.Entry(window,width=40)#这是输入框
g.grid(row=1, column=1,columnspan=1)

def se():#这是获取路径函数
    g.delete(0, "end")
#    path=filedialog.askdirectory()#这个是路径而已不好用
    path=filedialog.askopenfilename()
#    path=path.replace("/","\\\\")#通过replace函数替换绝对文件地址中的/来使文件可被程序读取 #注意:\\转义后为\,所以\\\\转义后为\\
    n=path.count('/')
    str=path.split('/')
    g.insert('insert',path)
    print('文件夹选择完毕,路径为:',path)
    print('字符串个数为:',n)
    print('最后一个文件为:',str[n])
b1 = tkinter.Button(window, text="打开", command=se)#这是按键
b1.grid(row=1, column=3)
# 定义button
b = tkinter.Button(window,text='退出',command=window.destroy)
b.grid(row=2, column=3)

window.mainloop()

猜你喜欢

转载自blog.csdn.net/weixin_44345862/article/details/127991405