下面的大部分代码都是为了准确复制问题,问题很可能是filename
从askopenfilenameI()
到printing(stringToPrint)
或{{1}的交接最后的陈述。
此程序的目标是在单击if
按钮时将文件路径打印到控制台。
执行程序时,窗口会正确显示,并允许您在文件系统中选择文件。打开文件后,脚本似乎在执行自己的Print File Path
语句之前调用printing
方法。当我打开另一个文件时,它只打印print
的打印语句(这是正确的)。
但是,单击askopenfilename()
按钮似乎在任何阶段都无法正常工作。
示例输出为:
点击价值:Print File Path
askopenfilename值:no-file
askopenfilename值:C:/Temp/AFTER_FIRST_OPEN.txt
C:/Temp/AFTER_SECOND_OPEN.txt
答案 0 :(得分:2)
问题的根源在于您在创建按钮时调用self.printing
。解决方案很简单:将self.printing(filename)
更改为self.printing
,然后self.printing
打印由self.askopenfilename
设置的属性。
例如:
class TkApp(Tkinter.Frame):
def __init__(self, root):
...
self.currentFile = None
...
Tkinter.Button(self, text='Open File', command=self.askopenfilename)
Tkinter.Button(self, text='Print File Path', command=self.printing)
...
def askopenfilename(self):
...
self.currentFile = tkFileDialog.askopenfilename(**self.file_opt)
...
def printing(self):
print "Value on click: " + self.currentFile
注意:从按钮调用的函数中的return
语句绝对没有用处。按钮的实际调用者忽略所有返回值。
答案 1 :(得分:1)
我认为问题是self.printing
函数在按下按钮时无法获取参数。这在许多GUI库中很常见。为了解决这个问题,我建议您将filename
更改为self.filename
,这样就可以从self.printing
调用它,即使它没有通过。
代码如下:
import Tkinter, Tkconstants, tkFileDialog
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}
#moved initiation of filename to here so it will print if no file has been selected
self.filename = 'no-file'
# define buttons
Tkinter.Button(self, text='Open File', command=self.askopenfilename).pack(**button_opt)
Tkinter.Button(self, text='Print File Path', command=self.printing).pack(**button_opt) #not the removal of variable.
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.
"""
# get filename - edited to be part of self
self.filename = tkFileDialog.askopenfilename(**self.file_opt)
# open file on your own
if self.filename:
print "askopenfilename value: " + self.filename
return self.filename
def printing(self):
print "Value on click: " + self.filename
def quit(self):
root.destroy()
if __name__=='__main__':
root = Tkinter.Tk()
root.title("Path Printer")
TkApp(root).pack()
root.mainloop()