I'm making a simple little utility while learning Python. It dynamically generates a list of buttons:
for method in methods:
button = Button(self.methodFrame, text=method, command=self.populateMethod)
button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})
That part works fine. However, I need to know which of the buttons was pressed inside self.populateMethod
. Any advice on how I might be able to tell?
To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.
To find out which button is the currently checked button, you can invoke the methods QButtonGroup. checkedButton() and QButtonGroup. checkedId() . The former will return a QButton object and the latter will return an index int , corresponding to the order in which the buttons were added to the group.
config is used to access an object's attributes after its initialisation. For example, here, you define. l = Label(root, bg="ivory", fg="darkgreen") but then you want to set its text attribute, so you use config : l.
You can use lambda to pass arguments to a command:
def populateMethod(self, method):
print "method:", method
for method in ["one","two","three"]:
button = Button(self.methodFrame, text=method,
command=lambda m=method: self.populateMethod(m))
button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})
It seems that the command method is not passed any event object.
I can think of two workarounds:
associate a unique callback to each button
call button.bind('<Button-1>', self.populateMethod)
instead of passing self.populateMethod as command
. self.populateMethod must then accept a second argument which will be an event object.
Assuming that this second argument is called event
, event.widget
is a reference to the button that was clicked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With