Python - 从 Tkinter 回调返回 [英] Python - returning from a Tkinter callback
问题描述
如何从作为 Tkinter 回调执行的函数中获取返回的对象?
How can I get a returned object 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 选择函数的参数,然后按下将执行函数的按钮.然而,函数的返回值似乎注定会丢失给以太,因为回调不会接受返回.如果在 square(x)
的定义中不使用丑陋的 global
,是否可以克服这个问题?
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)
...
如果您将应用程序创建为一个类,这将变得更加容易,并且您可以避免使用全局变量:
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屋!