pythontk界面显示函数中的变量值_python tkinter在函数之间传递变量

I am trying to pass the variable dirpath into the export_data() function. Export data runs off of a double click on a button located on a widget. Why is dirpath printing as:

``

instead of the actual path?

def export_data(dirpath):

print 'exporting...'

print str(dirpath)

os.mkdir('/home/bigl/Desktop/Library')

shutil.copytree(dirpath, output_path)

When I run my code I get the error

exporting...

Traceback (most recent call last):

File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__

return self.func(*args)

File "/media/LOFTUS/20130308_searchtest.py", line 44, in export_data

shutil.copytree(dirpath, output_path)

File "/usr/lib/python2.7/shutil.py", line 169, in copytree

names = os.listdir(src)

TypeError: coercing to Unicode: need string or buffer, instance found

解决方案

In the body of the question you asked:

Export data runs off of a double click on a button located on a

widget. Why is dirpath printing as:

When you bind to an event, the binding always sends an event object as a parameter to the bound function. So, if you're doing:

widget.bind("", export_data)

... then export_data will receive the event as it's only parameter.

To pass a variable, you need to use lambda or functools.partial or some sort of function generator. For example:

widget.bind("", lambda event: export_data(dirpath))

Be careful with this, however. The value passed to export_data will be the value of dirpath at the time the event occurs, which may be different than the value when you creating the binding.

If you have a local variable that you want to pass to the function you can set it as a default value to a keyword argument, in which case the value at the time the lambda is created will be passed.

Example:

path = some_function()

widget.bind("", lamba event, dirpath=path: export_data(dirpath))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值