I am not aware of any internal tkinter method to check if a button is pressed.
However you could connect the Button with a function that changes the value of a global variable, like in the following:
from Tkinter import *
master = Tk()
def callback():
global buttonClicked
buttonClicked = not buttonClicked
buttonClicked = False # Bfore first click
b = Button(master, text="Smth", command=callback)
b.pack()
mainloop()
The code, changes the variable value from False to True (or reverse) every time you press the button.
I am not aware of any internal tkinter method to check if a button is pressed.
However you could connect the Button with a function that changes the value of a global variable, like in the following:
from Tkinter import *
master = Tk()
def callback():
global buttonClicked
buttonClicked = not buttonClicked
buttonClicked = False # Bfore first click
b = Button(master, text="Smth", command=callback)
b.pack()
mainloop()
The code, changes the variable value from False to True (or reverse) every time you press the button.
I think that you could make a function to change the value of buttonClicked, and, when the button is clicked, it executes that function (whose only purpose is to change the value of buttonClicked).
The complete code could go as follows:
from tkinter import *
buttonClicked = False
def changeValue():
if buttonClicked:
buttonClicked=False
if not buttonClicked:
buttonClicked=True
tk = Tk()
btn = Button(tk, text="Put whatever text you want here, to tell the person what pressing the button will do", command=changeValue())
btn.pack()
If this answer help, I would appreciate you tell me! :).
This is a changed/edited version, with a loop for logic that changes the value of buttonClicked. In the part of code that says "if not buttonClicked:" you could change to an "else:" statement. @
[Tkinter] Button command is executed as soon as the program is run without pressing the button
python - Tkinter: Calling function when button is pressed - Stack Overflow
Python tkinter detecting which button is pressed
How to make button in Python Tkinter stay pressed until another one is pressed - Stack Overflow
Videos
I'm trying to create a button that shows a label and entry widget when pressed. However, the button, label and entry widget all show up without the button even being pressed. The following is my code:
from tkinter import *
main = Tk()
main.title('Test')
lbl1 = Label(main, text= 'BUTTON PRESSED')
ent1= Entry(main)
def onclick():
lbl1.grid(row=1, column= 0, padx=35, pady=5)
ent1.grid(row=3,column=0)
btn1 = Button(main, text = 'Press to Begin', command= onclick())
btn1.grid(row=0, column=0, padx=30, pady=4)
main.mainloop()
Here's a runnable answer. In addition to changing the commmand= keyword argument so it doesn't call the function when the tk.Buttons are created, I also removed the event argument from the corresponding function definitions since tkinter doesn't pass any arguments to widget command functions (and your function don't need it, anyway).
You seem to be confusing event handlers with widget command function handlers. The former do have an event argument passed to them when they're called, but the latter typically don't (unless you do additional stuff to make it happenโit's a fairly common thing to need/want to do and is sometimes referred to as theThe extra arguments trick).
import tkinter as tk
# added only to define required global variable "txt"
class Txt(object):
def SetValue(data): pass
def GetValue(): pass
txt = Txt()
####
def load():
with open(textField.get()) as file:
txt.SetValue(file.read())
def save():
with open(textField.get(), 'w') as file:
file.write(txt.GetValue())
win = tk.Tk()
win.title('Text Editor')
win.geometry('500x500')
# create text field
textField = tk.Entry(win, width=50)
textField.pack(fill=tk.NONE, side=tk.TOP)
# create button to open file
openBtn = tk.Button(win, text='Open', command=load)
openBtn.pack(expand=tk.FALSE, fill=tk.X, side=tk.TOP)
# create button to save file
saveBtn = tk.Button(win, text='Save', command=save)
saveBtn.pack(expand=tk.FALSE, fill=tk.X, side=tk.TOP)
win.mainloop()
Remove the 'event' arguments from both function defs and remove brackets from your commands.
So you can set the relief of the button using its config, this makes it look like it is pressed.
def save(self):
self.button0.config(relief=SUNKEN)
# if you also want to disable it do:
# self.button0.config(state=tk.DISABLED)
#...
def stop(self):
self.button0.config(relief=RAISED)
# if it was disabled above, then here do:
# self.button0.config(state=tk.ACTIVE)
#...
EDIT
This doesn't work on Mac OSx apparently. This link shows how in should look: http://www.tutorialspoint.com/python/tk_relief.htm
If Tkinter.Button doesn't allow to configure its relief property on your system then you could try ttk.Button-based code instead:
try:
import Tkinter as tk
import ttk
except ImportError: # Python 3
import tkinter as tk
import tkinter.ttk as ttk
SUNKABLE_BUTTON = 'SunkableButton.TButton'
root = tk.Tk()
root.geometry("400x300")
style = ttk.Style()
def start():
button.state(['pressed', 'disabled'])
style.configure(SUNKABLE_BUTTON, relief=tk.SUNKEN, foreground='green')
def stop():
button.state(['!pressed', '!disabled'])
style.configure(SUNKABLE_BUTTON, relief=tk.RAISED, foreground='red')
button = ttk.Button(root, text ="Start", command=start, style=SUNKABLE_BUTTON)
button.pack(fill=tk.BOTH, expand=True)
ttk.Button(root, text="Stop", command=stop).pack(fill=tk.BOTH, expand=True)
root.mainloop()
Set a flag when the button is pressed, unset the flag when the button is released. There's no need for a loop since you're already running a loop (mainloop)
from Tkinter import *
running = False
root = Tk()
def start_motor(event):
global running
running = True
print("starting motor...")
def stop_motor(event):
global running
print("stopping motor...")
running = False
button = Button(root, text ="forward")
button.pack(side=LEFT)
button.bind('<ButtonPress-1>',start_motor)
button.bind('<ButtonRelease-1>',stop_motor)
root.mainloop()
Assuming that you actually want to do something while the key is pressed, you can set up an animation loop using after. For example, to call a print statement once a second while the button is pressed you can add a function that does the print statement and then arranges for itself to be called one second later. The stop button merely needs to cancel any pending job.
Here's an example. The main difference to the original code is the addition of a move function. I also added a second button to show how the same function can be used to go forward or backward.
from Tkinter import *
running = False
root = Tk()
jobid = None
def start_motor(direction):
print("starting motor...(%s)" % direction)
move(direction)
def stop_motor():
global jobid
root.after_cancel(jobid)
print("stopping motor...")
def move(direction):
global jobid
print("Moving (%s)" % direction)
jobid = root.after(1000, move, direction)
for direction in ("forward", "backward"):
button = Button(root, text=direction)
button.pack(side=LEFT)
button.bind('<ButtonPress-1>', lambda event, direction=direction: start_motor(direction))
button.bind('<ButtonRelease-1>', lambda event: stop_motor())
root.mainloop()
You might want to try the repeatinterval option. The way it works is a button will continually fire as long as the user holds it down. The repeatinterval parameter essentially lets the program know how often it should fire the button if so. Here is a link to the explanation:
http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/button.html
Search in-page for "repeatinterval".
Another name for this parameter is repeatdelay.
I have multiple buttons being made and I want to call to a function using the button's name as one of the variables. How would I get the name of the button into the function?
You already had your event function. Just correct your code to:
"""Create Submit Button"""
self.submitButton = Button(master, command=self.buttonClick, text="Submit")
self.submitButton.grid()
def buttonClick(self):
""" handle button click event and output text from entry area"""
print('hello') # do here whatever you want
This is the same as in @Freak's answer except for the buttonClick() method is now outside the class __init__ method. The advantage is that in this way you can call the action programmatically. This is the conventional way in OOP-coded GUI's.
You should specify a handler, or a function, that is called when you click the Button. You can do this my assigning the name (not calling the function) of the function to the property command of your Button.
For example:
self.submitButton = Button(self.buttonClick, text="Submit", command=buttonClick)
Note the absence of () when assigning buttonClick as the command property of self.submitButton.
Note that you don't need the second parameter called event in your handler/function buttonClick().