tkinter.Button按下时运行一个函数弹起时运行另外 一个函数的示例
时间: 2024-05-12 13:14:55 浏览: 12
可以使用 `command` 参数来指定按钮按下时要运行的函数,使用 `bind` 方法来指定按钮弹起时要运行的函数。
下面是一个示例代码:
```python
import tkinter as tk
def on_button_press():
print("Button pressed")
def on_button_release(event):
print("Button released")
root = tk.Tk()
button = tk.Button(root, text="Click me", command=on_button_press)
button.pack()
button.bind("<ButtonRelease-1>", on_button_release)
root.mainloop()
```
在这个示例中,我们创建了一个名为 `on_button_press` 的函数,它将在按钮按下时运行。我们将这个函数作为 `command` 参数传递给了 `Button` 对象。
我们还创建了一个名为 `on_button_release` 的函数,它将在按钮弹起时运行。我们使用 `bind` 方法将这个函数绑定到了 `<ButtonRelease-1>` 事件上,这意味着它将在左键弹起时运行。
注意,我们在 `on_button_release` 函数中使用了一个名为 `event` 的参数。这是因为当事件发生时,`tkinter` 会自动将一个事件对象传递给绑定的函数。我们可以使用这个对象来获取有关事件的信息,例如事件发生的位置等。在这个例子中,我们没有使用这些信息,所以 `event` 参数实际上是多余的。