Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine which Button was pressed in Tkinter?

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?

like image 449
Sydius Avatar asked Oct 08 '09 18:10

Sydius


People also ask

How do I check if a button is pressed in Python?

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.

How do you check if a button has been clicked pyqt5?

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.

What is config () in Tkinter?

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.


2 Answers

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})
like image 58
Bryan Oakley Avatar answered Oct 02 '22 21:10

Bryan Oakley


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.

like image 24
Raphaël Saint-Pierre Avatar answered Oct 02 '22 23:10

Raphaël Saint-Pierre