This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 6 years ago.
I have the following lines in a large program.
username = Entry(loginPage)
password = Entry(loginPage)
button1 = Button(loginPage,text = "Login", fg = "red", command = loginClicked(username.get(),password.get()))
When the program is run, the function loginClicked runs once at the start (when the fields are empty and the button hasn't been clicked) and that is the only time it runs. After, when the button is clicked the function doesn't run at all. A print statement in the function confirms this.
As mentioned in the comments, when you create the widget you are calling ('running') the function before the widget is created, instead of passing the function handle (may be wrong terminology here) to the widget option command=.
This can be solved by using anonymous functions with lambda:
button1 = Button(root,text = "Login",
fg = "red",
command = lambda: loginClicked(username.get(), password.get()))
This creates a 'throw-away' function to feed into Tkinter's callback, which calls your function loginClicked() with its correct arguments.
You can also read effbot.org for more information on Tkinter callbacks
Related
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 1 year ago.
I have this following menu created in Tkinter
subMenu = Menu(Selection)
Selection.add_cascade(label = "Maze Generation Algorithms", menu = subMenu)
subMenu.add_command(label = "Recursive Back Tracking", command = FindNext(Stack[0], Stack, canvas, root))
The problem is when I start up my program, the FindNext function will automatically run without the menu button being pressed yet. How would I fix this?
Try to use lambda
subMenu.add_command(label = "Recursive Back Tracking", command = lambda:FindNext(Stack[0], Stack, canvas, root))
This question already has answers here:
tkinter creating buttons in for loop passing command arguments
(3 answers)
How to pass arguments to a Button command in Tkinter?
(18 answers)
Closed 6 months ago.
how to change values in buttons done in a loop?
I mean a different text, a command for each of the resulting buttons.
the program counts files in a given folder, then this value is passed to the loop that displays the appropriate number of buttons.
here is the sample text:
files = os.listdir(".")
files_len = len(files) - 1
print(files_len)
def add():
return
for i in range(files_len):
b = Button(win, text="", command=add).grid()
You don't really need to change the Button's text, because you can just put the filename in when they're created (since you can determine this while doing so).
To change other aspects of an existing Button widget, like its command callback function, you can use the universal config() method on one after it's created. See Basic Widget Methods.
With code below, doing something like that would require a call similar to this: buttons[i].config(command=new_callback).
To avoid having to change the callback function after a Button is created, you might be able to define its callback function inside the same loop that creates the widget itself.
However it's also possible to define a single generic callback function outside the creation loop that's passed an argument that tells it which Button is causing it to be called — which is what the code below (now) does.
from pathlib import Path
import tkinter as tk
win = tk.Tk()
dirpath = Path("./datafiles") # Change as needed.
buttons = []
def callback(index):
text = buttons[index].cget("text")
print(f"buttons[{index}] with text {text!r} clicked")
for entry in dirpath.iterdir():
if entry.is_file():
button = tk.Button(win, text=entry.stem,
command=lambda index=len(buttons): callback(index))
button.grid()
buttons.append(button)
win.mainloop()
Try this. By making a list.
files = os.listdir(".")
files_len = len(files) - 1
print(files_len)
def add():
return
b=[]
for i in range(files_len):
b[i] = Button(win, text="", command=add).grid(row=i)
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 5 years ago.
I am writing code to pass two variables to a function on the click of a button. The issue is that it is doing so before the button is pressed. What am I doing wrong?
calcButton = Button(window, text="Calculate Weight",
command=window.calc(5,10))
calcButton.place(x=225, y=85)
answertextLabel = Label(window, text="Answer:")
answertextLabel.place(x=225, y=65)
answerLabel = Label(window, text=answervar)
answerLabel.place(x=275, y=65)
def calc(window, diameter, density):
math = diameter + density
print (math)
When you do window.calc(5,10) the function gets executed.
You need to wrap it in another function:
command=lambda: window.calc(5,10)
You aren't passing the function as an argument to the Button constructor; you are passing the return value of one particular call to that function. Wrap the call in a zero-argument function to defer the actual call until the button is clicked.
calcButton = Button(window,
text="Calculate Weight",
command=lambda : window.calc(5,10))
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 7 years ago.
User inputs text into a text box clicks search and then the text is printed. Right now being printed in the shell is fine as I am still developing this. However, with everything I have read in the docs, what I am doing should work. So I am assuming its something small that I dont see. Please let me know what I am doing wrong.
def save():
key = entryName.get()
print(key)
nameField = StringVar()
entryName = Entry(root,textvariable= nameField)
entryName.grid(row=3,column=2)
searchButton = Button(root, text = "Search", command = save())
searchButton.grid(row = 19,column = 2)
The issue seems to be in the line -
searchButton = Button(root, text = "Search", command = save())
You should set the function directly as the value for command argument, not call it and set its return value as argument (which is None , since the function does not return anything) . Example -
searchButton = Button(root, text = "Search", command = save)
This question already has answers here:
Why is my Tk button being pressed automatically?
(2 answers)
Closed 8 years ago.
I'm using Python and TkInter to build a GUI where a certain command is called when a button is pressed. The relevant code looks like this:
class Main(Frame):
def __init__(self, parent):
self.generate_noise_button = Button(root, text="Add noise and save", command=self.generate_noise())
...
def generate_noise(self):
header.generate_noise()
If I place a breakpoint in the generate_noise() method and run the program, the breakpoint is instantly hit despite never being called or the button being pressed. Furthermore whenever I actually do press the button the method is never called making the button completely useless. Why?
self.generate_noise_button = Button(root, text="Add noise and save", command=self.generate_noise())
When you provide a command argument, you're not supposed to add parentheses to the end.
self.generate_noise_button = Button(root, text="Add noise and save", command=self.generate_noise)
You want the command to refer to the method object, not the value that the method returns after it is called.