示例图形用户界面:
假设我有 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 但不是该功能之外的任何地方。因此你宁愿调整在当前范围内可访问的对象。
使用 global 对象修改的完整示例
下面的示例将调用一个方法,该方法在每次按下按钮时更改 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