python tkinter在函数之间传递变量 [英] python tkinter passing variables between functions

查看:380
本文介绍了python tkinter在函数之间传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将变量dirpath传递到export_data()函数中。双击窗口小部件上的按钮即可导出数据。 dirpath为什么打印为:

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:

`<Tkinter.Event instance at 0x8ade56c>` 

而不是实际路径?

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...
<Tkinter.Event instance at 0x8ade56c>
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


推荐答案

在您问的问题正文中:


通过双击位于
小部件上的按钮可以导出数据。目录路径为什么打印为:

Export data runs off of a double click on a button located on a widget. Why is dirpath printing as:

< Tkinter.Event instance at 0x8ade56c>

绑定到事件时,绑定始终将事件对象作为参数发送到绑定函数。因此,如果您正在这样做:

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("<Double-1>", export_data)

...然后 export_data 会收到事件

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

要传递变量,您需要使用 lambda functools。部分或某种函数生成器。例如:

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

widget.bind("<Double-1>", lambda event: export_data(dirpath))

但是要小心。传递给 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.

如果要传递给函数的局部变量可以将其设置为关键字参数的默认值,在这种情况下,将创建 lambda

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.

示例:

path = some_function()
widget.bind("<Double-1>", lamba event, dirpath=path: export_data(dirpath))

这篇关于python tkinter在函数之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆