【发布时间】:2015-07-19 21:34:48
【问题描述】:
下面的大部分代码只是为了准确地复制问题,问题很可能是filename从askopenfilenameI()到printing(stringToPrint)或最后的if语句的交接。
目标
该程序的目标是在单击Print File Path 按钮时将文件路径简单地打印到控制台。
当前状态
当程序执行时,窗口会正确显示,它允许您在文件系统中选择一个文件。打开文件后,脚本似乎在执行自己的print 语句之前调用了printing 方法。当我打开另一个文件时,它会打印来自askopenfilename() 的唯一打印语句(这是正确的)。
但是,单击Print File Path 按钮似乎在任何阶段都不起作用。
一个示例输出是:
点击价值:no-file
askopenfilename 值:C:/Temp/AFTER_FIRST_OPEN.txt
askopenfilename 值:C:/Temp/AFTER_SECOND_OPEN.txt
代码
import Tkinter, Tkconstants, tkFileDialog
filename = 'no-file'
class TkApp(Tkinter.Frame):
def __init__(self, root):
Tkinter.Frame.__init__(self, root)
# options for buttons
button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
# define buttons
Tkinter.Button(self, text='Open File', command=self.askopenfilename).pack(**button_opt)
Tkinter.Button(self, text='Print File Path', command=self.printing(filename)).pack(**button_opt)
Tkinter.Button(self, text='Quit', command=self.quit).pack(**button_opt)
# define options for opening or saving a file
self.file_opt = options = {}
options['defaultextension'] = '.twb'
options['filetypes'] = [('All', '*')]
options['initialdir'] = 'C:\\'
options['parent'] = root
options['title'] = 'Select a File'
def askopenfilename(self):
"""Returns an opened file in read mode.
This time the dialog just returns a filename and the file is opened by your own code.
"""
global filename
# get filename
filename = tkFileDialog.askopenfilename(**self.file_opt)
# open file on your own
if filename:
print "askopenfilename value: " + filename
return filename
def printing(self, stringToPrint):
print "Value on click: " + stringToPrint
def quit(self):
root.destroy()
if __name__=='__main__':
root = Tkinter.Tk()
root.title("Path Printer")
TkApp(root).pack()
root.mainloop()
【问题讨论】:
-
command=self.printing(filename)参数实际上是在定义“打印文件路径”按钮时调用printing()函数。
标签: python python-2.7 tkinter