我做了一些這樣的功能:
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
def clicked(event):
print("Button pressed")
button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
b1 = Button(button_pos, 'Button1')
b1.on_clicked(clicked)
button_pos = plt.axes([0.2, 0.8, 0.1, 0.075])
b2 = Button(button_pos, 'Button2')
b2.on_clicked(clicked)
plt.show()
我現在的目標是在 clicked 函式中添加第二個引數。該函式現在具有以下形式:
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
def clicked(event, text):
print("Button pressed" text)
button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
b1 = Button(button_pos, 'Button1')
b1.on_clicked(clicked(text=" its the first"))
button_pos = plt.axes([0.2, 0.8, 0.1, 0.075])
b2 = Button(button_pos, 'Button2')
b2.on_clicked(clicked)
b2.on_clicked(clicked(text=" its the second"))
plt.show()
但是通過這種更改,我收到以下錯誤訊息:
Traceback (most recent call last):
File "/bla/main.py", line 24, in <module>
b1.on_clicked(clicked(text=" its the first"))
TypeError: clicked() missing 1 required positional argument: 'event'
他們是在這樣的函式中放置第二個引數的方法,還是在這種情況下需要在 Python 中創建兩個 on_clicked 函式?
uj5u.com熱心網友回復:
你的第二個代碼的問題是你在clicked里面使用它時呼叫了該函式b1.on_clicked。這會引發錯誤。
而是b1.on_clicked將一個函式作為引數,然后在后臺呼叫該函式,將事件作為引數傳遞。
你可以這樣做
def fn_maker(text=''):
def clicked(event):
print(f"Button pressed{text}")
return clicked
button_pos = plt.axes([0.2, 0.9, 0.1, 0.075])
b1 = Button(button_pos, 'Button1')
b1.on_clicked(fn_maker(text=" its the first"))
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362620.html
標籤:Python matplotlib 按钮 点击 争论
