AttributeError: StringVar instance has no attribute 'endswith' while trying to call from a Tkinter button

AttributeError: StringVar instance has no attribute 'endswith' while trying to call from a Tkinter button

我想创建一个接收两个路径的 GUI(一个充满 .txt 文档的目录和一个从前面提到的文件夹的文件创建的新 .csv 文件的目标)。

我在调用函数时遇到问题 munge():

action = tk.Button(win, text="To .csv",command=munge(input_directory,output_directory))

然而,引发了这个异常:

/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/user/PycharmProjects/script.py
Traceback (most recent call last):
  File "/Users/user/PycharmProjects/script.py", line 82, in <module>
    action = tk.Button(win, text="To .csv", command=munge(input_directory,output_directory))
  File "/Users/user/PycharmProjects/script.py", line 39, in munge
    test = tuple(retrive(directory))
  File "/Users/user/PycharmProjects/script.py", line 31, in retrive
    for filename in sorted(glob.glob(os.path.join(directory_path, '*.txt'))):
  File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 70, in join
    elif path == '' or path.endswith('/'):
AttributeError: StringVar instance has no attribute 'endswith'

Process finished with exit code 1

如何借助按钮小部件正确调用上述功能?我尝试按照此处 question 的指示设置变量的名称,但没有成功。

更新

然后根据这个问题的答案,我尝试了以下方法:

action = tk.Button(win, text="To .csv", command=lambda:munge(input_directory,output_directory))

您想调用 StringVar 的 .get() 方法来获取它包含的字符串,否则它只是 StringVar 实例。

您可能需要考虑阅读一些关于 Tkinter 中的回调函数的内容,这里有一个有用的 link http://effbot.org/zone/tkinter-callbacks.htm:

For simple cases like this, you can use a lambda expression as a link between Tkinter and the callback function:

def callback(number):
    print "button", number

Button(text="one",   command=lambda: callback(1))

您的函数在您的 Button 小部件加载后立即执行,您希望避免这种情况。

根据错误消息,您似乎正在尝试调用 StringVar 对象的 endswith 方法。如果您查看此类对象的文档,您会发现没有此类方法。这就是为什么你会得到你所做的错误。

假设 pathStringVar 的实例,您必须调用 get 方法才能让对象存储字符串:

path_string = path.get()
if path_string == "" or path_string.endswith('/'):
    ...

毕竟,它适用于:action = tk.Button(win, text="To .csv", command=lambda:munge(input_directory.get(),output_directory.get()))。但是,根据 Bryan Oakley 的回答,我认为这不是正确的方法。