Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to press a button without touching it on tkinter / python?

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! :)

like image 765
Bryan Black Avatar asked May 24 '14 00:05

Bryan Black


2 Answers

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.

like image 175
A.J.Bauer Avatar answered Nov 02 '22 06:11

A.J.Bauer


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.

like image 31
Lily Chung Avatar answered Nov 02 '22 04:11

Lily Chung