图形用户界面示例:
假设我有 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选项应该设置为,对我们要调用的方法的引用,类似于button_press_handle中的callback。
没有参数
所以如果我想在按下按钮时print 某些东西,我需要设置:
btn['command'] = print # default to print is new line
密切注意() 的缺少 与print 方法省略的意思是:“这是我希望你调用的方法的名称按下 但不要立即调用它。” 但是,我没有为 print 传递任何参数,所以它打印了在不带参数调用时打印的任何内容。
有个参数
现在,如果我还想在按下按钮时将参数传递给 我想要调用的方法,我可以使用匿名函数,可以使用 lambda 语句创建,在本例中为 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 = 0
def 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 modified
root = tk.Tk()
btn = tk.Button(root, text="My Button")
btn['command'] = text_mod
btn.pack(fill='both', expand=True)
root.mainloop()
Mirror