To Detect Button Press In Python Tkinter Module - python

I have a problem to detect/check button press in python tkinter !
I have a variable click i want that if my button is clicked then it becomes True
for ex:
this is my code:
buttonClicked=False
myButton=Button()
I want something like this:
if myButton is pressed:
buttonClicked=True
Thanks for your help!

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. #

Try this:
from tkinter import *
value = 1
def change_value():
global value
value -= 1
if value == 0:
print("button pressed")
value = 1
else:
pass
tk = Tk()
btn = Button(tk, text="your_text", command=change_value)
btn.pack()

Just put the code you want to run inside a function like this:
def when_clicked():
#code you want here
button = Button(window,command=when_clicked)
(may be a bit late but oh well)

Related

Get dynamically which button uses function

I have a question about buttons and binds, but it's better if I show you.
from tkinter import Tk,Button
root = Tk()
startbutton = Button(root,text="start button")
pingbutton = Button(root,text="ping button")
startbutton.pack()
pingbutton.pack()
def startenterbind(e):
startbutton.config(relief='sunken')
def startleavebind(e):
startbutton.config(relief='raised')
def pingenterbind(e):
pingbutton.config(relief='sunken')
def pingleavebind(e):
pingbutton.config(relief='raised')
startbutton.bind("<Enter>", startenterbind)
startbutton.bind("<Leave>", startleavebind)
pingbutton.bind("<Enter>", pingenterbind)
pingbutton.bind("<Leave>", pingleavebind)
root.mainloop()
This is my code, now I am wondering, is there a better way to do this?
Maybe it's possible to get which button was hovered dynamically, to then change the button that was hovered?
This is so I can use one function for multiple buttons, while only affecting the one being <Enter>'d or <Leave>'d?
You can reuse an event handler function by making use of the event object they are passed which has an attribute telling you the widget that triggered it.
from tkinter import Tk,Button
root = Tk()
startbutton = Button(root,text="start button")
pingbutton = Button(root,text="ping button")
startbutton.pack()
pingbutton.pack()
def startenterbind(event):
event.widget.config(relief='sunken')
def startleavebind(event):
event.widget.config(relief='raised')
startbutton.bind("<Enter>", startenterbind)
startbutton.bind("<Leave>", startleavebind)
pingbutton.bind("<Enter>", startenterbind)
pingbutton.bind("<Leave>", startleavebind)
root.mainloop()
You could go a bit further by writing a single function that simply toggled the state of the button whenever it was called. One way that could be accomplished is by making the new relief type depend on what it currently is which can be determined by calling the universal widget cget() method:
def enterleavebind(event):
new_relief = 'sunken' if event.widget.cget('relief') == 'raised' else 'raised'
event.widget.config(relief=new_relief)
startbutton.bind("<Enter>", enterleavebind)
startbutton.bind("<Leave>", enterleavebind)
pingbutton.bind("<Enter>", enterleavebind)
pingbutton.bind("<Leave>", enterleavebind)

Cant break loop using button

I wanted make window which will reappear if closed but will only close if user presses a button. I tried so many times but cant make. Plz help.
from Tkinter import *
x='y'
while x!='break':
def something(x):
x='break'
root=tkinter.Tk()
button=tkinter.Button(root, text='Break', command=lambda:something(x))
button.pack()
root.mainloop()
print('done')
When you set x using x = "break", you set the local variable which means that the global variable x is still "y". So to solve your problem just make sure that you use the global variable for x. This is a simple example:
import tkinter as tk
def something():
# Use the global variable for `loop_running`
global loop_running
loop_running = False
# You might also want to add: root.destroy()
loop_running = True
while loop_running:
root = tk.Tk()
button = tk.Button(root, text="Break", command=something)
button.pack()
root.mainloop()
print("Done")

Tkinter: How to update a label text after a certain amount of time has passed?

So, I'm trying to create a basic Tkinter program which, when I press a button, updates the text on a label field, waits X amount of seconds and then update the label again.
For example:
I click the button, the label clears immediately after pressing it, then the program waits 3 seconds and shows "Hello" on screen.
The code shown below does not do what I want it to do because when I press the button, it remains pressed for X amount of time and then the text is updated inmediately. I want to press the button, clear the label, wait for 3 seconds and then show "Hello" on screen.
from tkinter import *
class Origin:
def __init__(self):
self.root = Tk()
self.root.geometry('800x600')
self.root.config(bg="black")
self.v = StringVar()
self.v.set('O R I G I N')
self.main_label = Label(self.root, textvariable=self.v, font="Arial 40", fg="white", bg="black")
self.main_label.place(x=240, y=150)
self.clear = Button(self.root, text='Clear', command=self.clear)
self.clear.place(x=400, y=400)
self.root.mainloop()
def clear(self):
#just to clear the string
self.v.set('')
self.root.after(3000, self.v.set('Hello'))
def main():
App = Origin()
if __name__ == '__main__':
main()
after needs callback - it means function's name without () and arguments. If you have to use function with argument then use `lambda
after(3000, lambda:self.v.set('Hello'))
or create function which doesn't need arguments
def callback():
self.v.set('Hello')
self.root.after(3000, callback)
Your current code works like
result = self.v.set('Hello')
self.root.after(3000, result)
It executes function self.v.set('Hello') at once and uses its result as callback in after().
EDIT: as #acw1668 said in comment you can also run function with arguments this way
self.root.after(3000, self.v.set, 'Hello')

Python 3 tkinter message box highlight the "No" button?

I want to create a message box that confirms the intent to delete.
def delete_action(self):
s_id = self.selected_ID_entry.get()
s_name = self.seletedEntry.get()
answer = messagebox.askquestion("Delete?","Are you sure you want to delete {}".format(s_name), icon='warning')
if answer == 'yes':
#deleted function here
else:
#not deleted function here
How to highlight the "No" button instead of the "Yes" button?
You can set a default value as a keyword argument; something like this:
import tkinter as tk
from tkinter import messagebox
def quid():
messagebox.askyesno("What", "What???????????", default='no')
root = tk.Tk()
ask = tk.Button(root, text='what?', command=quid)
ask.pack()
root.mainloop()

Trying to print the output from my function inside my GUI window

Im trying to make a little program that endlessly prints out numbers inside GUI window, I can not find a way to print the out put of the function in a text box inside the GUI window instead of the python shell, please help, here is my code so far...
import sys
from tkinter import *
root = Tk()
def number(event):
x = 420
while True:
x +=420
print(x^70)
button_1 = Button(root, text="Start...")
button_1.bind("<Button-1>", number)
button_1.pack()
root.mainloop()
Thanks Harvey
You'll find it hard to constantly insert a value into a widget. The widget does not update with each insert. You can think of it has having a temporary variable for it. It can be accessed during the loop (as shown with print). However you'll notice that the widget itself doesn't update until the loop is over. So if you have while True then your widget will never update, and so you won't have the numbers streaming into the widget.
import sys
from tkinter import *
root = Tk()
def number():
x = 420
while x < 8400: # Limit for example
x +=420
textbox.insert(END, str(x^70)+'\n')
print(textbox.get(1.0, END)) # Print current contents
button_1 = Button(root, text="Start...", command=number) #Changed bind to command, bind is not really needed with a button
button_1.pack()
textbox = Text(root)
textbox.pack()
root.mainloop()

Categories

Resources