在定义的参数中使用事件

问题描述 投票:0回答:1

我正在尝试定义一个定义,包括事件(您知道,了解点击位置)和其他四个参数。我想称呼它,但我不知道怎么做。我试图给它提供一个默认值,但没有成功,我不知道用什么代替“事件”]

我的代码是:

def example(event,a,b,c,d):
python events tkinter definition
1个回答
0
投票

您的绑定函数将已经在tkinter的系统中像callback(event)一样被调用,因此def标头默认情况下采用一个位置参数,通常写为def callback(event):并与some_widget.bind(sequence, callback)绑定,只是将函数对象传递给bind并让event在内部传递。

话虽这么说,在事件回调中有两种方法可以从外部使用其他变量,并且仍然使用event对象。

  1. 使用lambda作为包装器传递任意args
a, b, c, d = some_bbox
def on_click(event, a, b, c, d):
  print(event.x, event.y, a, b, c, d)
  # do the rest of your processing
some_widget.bind("<Button-1>", lambda event, a=a, b=b, c=c, d=d: on_click(event, a, b, c, d)
  1. 使用globalnonlocal关键字指定要从外部范围获取的变量:
a, b, c, d = some_bbox
def on_click(event):
  # use global if a, b, c, and d exist at the module level
  global a, b, c, d
  # use nonlocal if a, b, c, and d exist within the scope of another function
  # nonlocal a, b, c, d
  print(event.x, event.y, a, b, c, d)
  # do the rest of your processing
some_widget.bind("<Button-1>", on_click)

python 3.8 tkinter 8.6

© www.soinside.com 2019 - 2024. All rights reserved.