示例GUI:
假设我有GUI:import tkinter as tk
root = tk.Tk()btn = tk.Button(root, text="Press")btn.pack()root.mainloop()
按下按钮会发生什么?
看看什么时候btn按下它的呼叫它自己的函数,非常类似于button_press_handle在以下示例中:def button_press_handle(callback=None):
if callback:
callback() # Where exactly the method assigned to btn['command'] is being callled
有:button_press_handle(btn['command'])
你可以简单地认为command选项应该设置为,对我们希望调用的方法的引用,类似于callback在……里面button_press_handle.
调用方法(回调)当按下按钮时
无论点
所以如果我想print当按下按钮时,我需要设置:btn['command'] = print # default to print is new line
密切关注缺的()带着print方法,该方法的含义是:“这是方法的名称,我希望您在按下时调用它但别这么快就打电话给我。“但是,我没有为print所以它在调用时不带任何参数地打印它所打印的任何东西。
带着论点
如果我也想把参数传递给我想被调用的方法当按下按钮时,我可以使用匿名函数,这些函数可以用兰卜达语句,在本例中print内置方法,如下所示:btn['command'] = lambda arg1="Hello", arg2=" ", arg3="World!" : print(arg1 + arg2 + arg3)
呼叫倍数方法时,按下按钮。
无论点
您也可以使用lambda语句,但是它被认为是错误的实践,因此我将在这里不包括它。好的做法是定义一个单独的方法,multiple_methods,它调用所需的方法,然后将其设置为按钮按下的回调:def multiple_methods():
print("Vicariously") # the first inner callback
print("I") # another inner callback
带着论点
为了将参数传递给调用其他方法的方法,再次使用lambda声明,但首先:def multiple_methods(*args, **kwargs):
print(args[0]) # the first inner callback
print(kwargs['opt1']) # another inner callback
然后设置:btn['command'] = lambda arg="live", kw="as the" : a_new_method(arg, opt1=kw)
从回调返回对象
还注意到callback不能真的return因为它只在里面被调用button_press_handle带着callback()相对于return callback()..是的return但不在这个功能之外的任何地方。所以你应该修改对象,该对象可在当前范围内访问。
完整的例子全球对象修改
下面的示例将调用一个更改的方法btn每次按下按钮时的文本:import tkinter as tk
i = 0def text_mod():
global i, btn # btn can be omitted but not sure if should be
txt = ("Vicariously", "I", "live", "as", "the", "whole", "world", "dies")
btn['text'] = txt[i] # the global object that is modified
i = (i + 1) % len(txt) # another global object that gets modifiedroot = tk.Tk()btn = tk.Button(root, text="My Button")
btn['command'] = text_mod
btn.pack(fill='both', expand=True)root.mainloop()