#-*- coding:utf:8 -*-
from Tkinter import *
from tkFont import Font
from ttk import *
from tkMessageBox import *
import os
'''
首先,__init__有两个参数。第一个是self,即Application_ui对象本身。
第二个是master,在Tkinter中,一个控件可能属于另一个控件,这时另一个控件就是这个控件的master。
默认一个窗口没有master,因此master有None的默认值。
第二行Frame.__init__(self, master)调用Application_ui的父类Frame的__init__函数初始化Application_ui类的Frame类部分。
__init__函数的定义如下:
__init__(self, master=None, cnf={}, **kw)
初始化Frame对象。master为Frame的父控件,默认为None;cnf尚不清楚;kw为命名关键字参数,可接受的参数将在后面提到。
'''
class Application_ui(Frame):
#这个类仅实现界面生成功能,具体事件处理代码在子类Application中。
def __init__(self,master = None):
Frame.__init__(self,master)
self.master.geometry('600x400')
self.createWidgets()
def createWidgets(self):
self.top = self.winfo_toplevel()
self.style = Style()
self.style.configure('TCommanddirectory.TButton', background='#FFFFFF', font=('Times New Roman',12,'bold'))
self.Commanddirectory = Button(self.top, text='访问目录', command=self.start, style='TCommanddirectory1.TButton')
self.Commanddirectory.grid(row=0, column=0, rowspan=2, padx=10, pady=10)
self.listbox0 = Listbox(self.top, height=20, width=60)
self.listbox0.grid(row=1, column=1, rowspan=2, padx=10, pady=10)
header = 'filename'
self.listbox0.insert(END,header)
self.listbox0.itemconfig(0,fg="black")
self.listbox0.itemconfig(0,bg="grey")
#双击事件绑定
self.listbox0.bind('<Double-Button-1>',self.openfile)
class Application(Application_ui):
#这个类实现具体的事件处理回调函数。界面生成代码在Application_ui中。
def __init__(self,master=None):
Application_ui.__init__(self, master)
def start(self):
l = []
dirs = os.listdir(os.getcwd())#os.getcwd():获取当前路径
for file in dirs:
l.append(file)
for i in range(len(l)):
if '.py' in l[i]:
to_add = ' %s' % (l[i])
self.listbox0.insert(1, to_add)
if i % 2:
self.listbox0.itemconfig(1,fg="#4B0082")
else:
self.listbox0.itemconfig(1,bg="#EDEDED")
#定义两个参数,一个是self,一个是event
#将idle路径加入环境变量后,利用命令行的方式访问文件
def openfile(self, event):
#获取所点击的文件的名称
filename = self.listbox0.get(self.listbox0.curselection())
#idle打开py文件
#cmd = "idle " + filename
#txt打开py文件
cmd = "notepad "+filename
os.system(cmd)
if __name__ == "__main__":
top = Tk()
top.title('python学习结果一览')
Application(top).mainloop()
try: top.destroy()
except: pass
实现内容:
使用tkinter图形化界面,点击按钮访问文件夹下所有py文件,双击listbox中每个py文件的名字能运行该文件。(可以用python 自带的idle打开,也可以用txt打开)
实现关键:
1.listbox双击绑定事件bind的使用
2.环境变量下添加idle路径
3.使用python的cmd访问
结果: