看了下Tkinter的文档,对于Pop-up dialog有三类,现在用到的是tkFileDialog
tkFileDialog有两种形式:
一个是.askopenfilename(option=value, ...) 这个是"打开"对话框
另一个是:asksaveasfilename(option=value, ...) 这个是另存为对话框
option参数如下:
defaultextension = s 默认文件的扩展名
filetypes = [(label1, pattern1), (label2, pattern2), ...] 设置文件类型下拉菜单里的的选项
initialdir = D 对话框中默认的路径
initialfile = F 对话框中初始化显示的文件名
parent = W 父对话框(由哪个窗口弹出就在哪个上端)
title = T 弹出对话框的标题
如果选中文件的话,确认后会显示文件的完整路径,否则单击取消的话会返回空字符串
-
- import Tkinter, Tkconstants, tkFileDialog
-
- class TkFileDialogExample(Tkinter.Frame):
-
- def __init__(self, root):
-
- Tkinter.Frame.__init__(self, root)
-
-
- button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
-
-
- Tkinter.Button(self, text='askopenfile', command=self.askopenfile).pack(**button_opt)
- Tkinter.Button(self, text='askopenfilename', command=self.askopenfilename).pack(**button_opt)
- Tkinter.Button(self, text='asksaveasfile', command=self.asksaveasfile).pack(**button_opt)
- Tkinter.Button(self, text='asksaveasfilename', command=self.asksaveasfilename).pack(**button_opt)
- Tkinter.Button(self, text='askdirectory', command=self.askdirectory).pack(**button_opt)
-
-
- self.file_opt = options = {}
- options['defaultextension'] = '.txt'
- options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
- options['initialdir'] = 'C:\\'
- options['initialfile'] = 'myfile.txt'
- options['parent'] = root
- options['title'] = 'This is a title'
-
-
-
-
-
-
-
-
- self.dir_opt = options = {}
- options['initialdir'] = 'C:\\'
- options['mustexist'] = False
- options['parent'] = root
- options['title'] = 'This is a title'
-
- def askopenfile(self):
-
-
-
- return tkFileDialog.askopenfile(mode='r', **self.file_opt)
-
- def askopenfilename(self):
-
-
-
-
- filename = tkFileDialog.askopenfilename(**self.file_opt)
-
-
- if filename:
- return open(filename, 'r')
-
- def asksaveasfile(self):
-
-
-
- return tkFileDialog.asksaveasfile(mode='w', **self.file_opt)
-
- def asksaveasfilename(self):
-
-
-
-
- filename = tkFileDialog.asksaveasfilename(**self.file_opt)
-
-
- if filename:
- return open(filename, 'w')
-
- def askdirectory(self):
-
-
-
- return tkFileDialog.askdirectory(**self.dir_opt)
-
- if __name__ == '__main__':
- root = Tkinter.Tk()
- TkFileDialogExample(root).pack()
- root.mainloop()