Why Is the Command Bound to a Button or Event Executed When Declared

Why is Button parameter command executed when declared?

It is called while the parameters for Button are being assigned:

command=Hello()

If you want to pass the function (not it's returned value) you should instead:

command=Hello

in general function_name is a function object, function_name() is whatever the function returns. See if this helps further:

>>> def func():
... return 'hello'
...
>>> type(func)
<type 'function'>
>>> type(func())
<type 'str'>

If you want to pass arguments, you can use a lambda expression to construct a parameterless callable.

>>> hi=Button(frame, text="Hello", command=lambda: Goodnight("Moon"))

Simply put, because Goodnight("Moon") is in a lambda, it won't execute right away, instead waiting until the button is clicked.

Button parameter “command” executes when declared, but not when pressed

bind and command= expect "function name" - it means without () and arguments.

If you need to assign function with arguments then use lambda

Button(..., command=lambda:button_map_set(x, y))

or create function without arguments

def test():
button_map_set(x, y)

Button(..., command=test)

if you need run more functions when you press button then use function

def test():
button_map_set(x, y)
button_map()

Button(..., command=test)

-

The same is with bind but bind sends event so function has to receive this information

def test(event):
button_map_set(x, y)
button_map()

btn.bind("<Button-1>", test)

<Button-1> means left mouse click.

-

If you need use the same functions with bind and command= you can use default value None for event

def test(event=None):
button_map_set(x, y)
button_map()

Button(..., command=test) # run `test(None)`
btn.bind("<Button-2>", test) # run `test(event)`

<Button-2> means right mouse click.


BTW: own button with 3 colors

import tkinter as tk

class MyButton(tk.Button):

colors = ['red', 'blue', 'orange']

def __init__(self, *args, **kwargs):
tk.Button.__init__(self, *args, **kwargs)

# current color number
self.state = 0

# set color
self.config(bg=self.colors[self.state])

# assign own function to click button
self.config(command=self.change_color)

def change_color(self):
# change current color number
self.state = (self.state + 1) % len(self.colors)

# set color
self.config(bg=self.colors[self.state])



root = tk.Tk()

for __ in range(5):
MyButton(root, text="Hello World").pack()

root.mainloop()

You can add more colors to the list colors and it will work too.

The buttons commands are automatically being executed in tkinter

All functions with () will be executed immediately. Try to wrap your function print(i) into lambda function like that command=lambda _: print(i) and call it with command()

Python: Button's command event being called before any click

You're calling submit_login when you bind it to the button:

command=submit_login(txt_username.get(), txt_password.get())

Instead, in Tkinter you can bind the command to a lambda:

command=lambda username=txt_username.get(), password=txt_password.get(): submit_login(username, password)

You'll probably also want to move your call to .get() so that it happens at the time of the click:

btn_login = tk.Button(frm_login, text='Login', font=(global_font, 16), bg=global_bg, fg=global_fg,    
command=lambda username=txt_username, password=txt_password: submit_login(username, password)


def submit_login(username, password):
username = username.get()
password = password.get()
if len(username) > 0 and len(password) > 0:
print('Username: ', username, ' | Password: ', password)
else:
print('One of the fields is not filled.')

Tkinter button bound to Enter immediately executes

When you call root.bind for <Return> you are passing the result of calling indiv_DTR(...) as a parameter. This is equivalent to the following:

res = indiv_DTR(rightFrame, empNumberToShow, beginDateToShow, endDateToShow, requiredReport)
root.bind('<Return>', res)

which should make it clearer that the function has already been executed.

To have the bind operation actually call this function you pass the method name. eg:

def onReturn(ev):
# call the indiv_DTR function

root.bind('<Return>', onReturn)

Or you can provide a lambda expression if you need some local variables to be captured as parameters to the event handler.

Tkinter button automatically runs command even if not pressed

Its because you are calling it instead of binding it

for i in range(0,2):
def onClick(i=i):# not good practice but demonstrates
print("You clicked I",i)
course[i] = Button(window,text=str(course[i]))
course[i].config(command=onClick) # notice i dont call onClick


Related Topics



Leave a reply



Submit