15

Hi I need to do this because, I am making a matching / memmory game, and there has to be a button (Totally separated from the ones on the current game) that when I press it, it has to show the matching cards automatically without having to touch the buttons with the mouse.

Is there a "press" function or something like that for pressing the button?

Thanks! :)

Bryan Black
  • 341
  • 2
  • 5
  • 13
  • 1
    What user input is supposed to cause the button to be pressed, if not a mouse click? If you just want the program to display the stuff without the user doing something, you don't need to simulate a button press; you can just trigger the function the button press would have activated. – user2357112 May 24 '14 at 00:10
  • 4
    I suggest you separate the UI logic from the game logic a little bit. Rather than pressing the button programmatically, just call the same callback (the thing you put in the `command=` argument). – Joel Cornett May 24 '14 at 00:10

2 Answers2

18

As Joel Cornett suggests in a comment, it might make more sense to simply call the callback that you passed to the button. However, as described in the docs, the Button.invoke() method will have the same effect as pressing the button (and will return the result of the callback), with the slight advantage that it will have no effect if the button is currently disabled or has no callback.

jackw11111
  • 1,457
  • 1
  • 17
  • 34
Lily Chung
  • 2,919
  • 1
  • 25
  • 42
  • 2
    Note: when the button is pressed, it highlights and remains highlighted until the callback completes. You lose this behavior if you call the callback directly. – Tobias Hagge Sep 25 '16 at 22:28
  • This is good for simulating user activity, for example in a (Classic) Mac OS 1983 Monkey-style fuzzer. – wizzwizz4 Jul 08 '17 at 12:00
6

If you also want visual feedback for the button you can do something like this:

from time import sleep

# somewhere the button is defined to do something when clicked
self.button_save = tk.Button(text="Save", command = self.doSomething)

# somewhere else 
self.button_save.bind("<Return>", self.invoke_button)

def invoke_button(self, event):
    event.widget.config(relief = "sunken")
    self.root.update_idletasks()
    event.widget.invoke()
    sleep(0.1)
    event.widget.config(relief = "raised")

In this example when the button has focus and Enter/Return is pressed on the keyboard, the button appears to be pressed, does the same thing as when clicked (mouse/touch) and then appears unpressed again.

A.J.Bauer
  • 2,803
  • 1
  • 26
  • 35