Python - 从Tkinter回调返回 [英] Python - returning from a Tkinter callback

查看:3126
本文介绍了Python - 从Tkinter回调返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从作为Tkinter回调函数执行的函数中获取返回的对象(或变量,或其他任何东西 - 它们基本上都是一样的)?

How can I get a returned object (or variable, or whatever - they're all basically the same, aren't they) from a function that is executed as a Tkinter callback?

import Tkinter as Tk
from functools import partial

def square(x):
    return x*x

root = Tk.Tk()
var = Tk.IntVar(root, value=0) #the variable the gets passed to the class call
menu = Tk.OptionMenu(root, var, *[0,1,2,3,4,5]) #a drop-down list to choose a value for the variable
menu.pack()
button = Tk.Button(root, text='click', command = partial(square,var.get())) #a button that calls the class
button.pack()
root.mainloop()

显然这是一个简化的例子。实际上,按钮调用的函数将返回对象,我希望将它们附加到将被保存在主Python命名空间中的对象列表中以进行进一步的操作。

Obviously this is a simplified example. In reality the function called by the button will return objects, which I wish to append to a list of objects that will be held in the main Python namespace for further operations.

无论如何,在这里用户能够使用GUI选择函数的参数,并按下将执行该函数的按钮。然而,函数的返回值似乎注定丢失到aether,因为回调将不接受返回。在 square(x)

Anyway, here the user is able to choose an argument for the function using a GUI, and press a button that will execute the function. The return value of the function, however, seems doomed to be lost to the aether, since the callback won't accept returns. Can this be overcome without the use of an ugly global in the definition of square(x)?

推荐答案

从回调中返回值的概念在事件驱动程序的上下文中没有意义。回调被称为事件的结果,所以没有地方可以返回值。

The notion of "returning" values from callbacks doesn't make sense in the context of an event driven program. Callbacks are called as the result of an event, so there's nowhere to return a value to.

作为一般的经验法则,你的回调应该总是调用一个函数,而不是使用 functools.partial lambda 。这两个在需要时是很好的,但是如果你使用面向对象的编码风格,它们通常是不必要的,并且导致代码比它需要的更难维护。

As a general rule of thumb, your callbacks should always call a function, rather than using functools.partial or lambda. Those two are fine when needed, but if you're using an object-oriented style of coding they are often unnecessary, and lead to code that is more difficult to maintain than it needs to be.

例如:

def compute():
    value = var.get()
    result = square(value)
    list_of_results.append(result)

button = Tk.Button(root, text='click', command = compute)
...

这变得更容易,并且可以避免全局变量,如果您将应用程序创建为class:

This becomes much easier, and you can avoid global variables, if you create your application as a class:

class App(...):
    ...
    def compute():
        ...
        result = self.square(self.var.get())
        self.results.append(result)

这篇关于Python - 从Tkinter回调返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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