Ask coding questions

← Back to all posts
WHY WHEN I RUN CODE BUTTON JUST DO COMMAND BEFORE I CLICK IT?
kachenXDEXE

import tkinter as tk
wincal = tk.Tk()
wincal.geometry("250x300")
wincal.configure (background = 'black')
wincal.title ('THIS IS LEGIT')

bt1 = tk.Button(master=wincal,bd=9,text='LEGIT',command=print('this is legit'))
bt1.place(x=90,y=80)

wincal.mainloop()

when i run this code it print (this is legit ) but I doesnt click button

Voters
kachenXDEXE
Comments
hotnewtop
NFadhlurrahman

The command argument receives a function, so you have to create a function or use lambda function.

kachenXDEXE

@NFadhlurrahman Must it always use lambda?
because i created function and use it in code like this
import tkinter as tk
wincal = tk.Tk()
wincal.geometry("250x300")
wincal.configure (background = 'black')
wincal.title ('THIS IS LEGIT')

def showtext(str):
print(str)

bt1 = tk.Button(master=wincal,bd=9,text='LEGIT',command=showtext('this is legit'))
bt1.place(x=90,y=80)

wincal.mainloop()

but it still run before i press it
but if i use lambda like this

bt1 = tk.Button(master=wincal,bd=9,text='LEGIT',command=lambda:showtext('this is legit'))
bt1.place(x=90,y=80)

so the answer is yes right thanks for information but can you explain more please

kachenXDEXE

@NFadhlurrahman im newbie thanks for give and attendtion to my stupid post
you are so clever

NFadhlurrahman

@kachenXDEXE

Must it always use lambda?

No. You can use either normal function or lambda function.

Also, this is not the right way to use normal function.

Like what I said, command argument receives a function, but in your example, it receives None instead of a function.

Here is the right way to use normal function

kachenXDEXE

@NFadhlurrahman so its mean i cant set the option if i want to use function in button but i use this command its work for set option and when i pressed its run the command
import tkinter as tk
wincal = tk.Tk()
wincal.geometry("250x300")
wincal.configure (background = 'black')
wincal.title ('THIS IS LEGIT')

def showtext(str):
print(str)

bt1 = tk.Button(master=wincal,bd=9,text='LEGIT',command=lambda:
showtext('this is legit'))
bt1.place(x=90,y=80)

wincal.mainloop()

and when i use it its work very well and there is no error

kachenXDEXE

@NFadhlurrahman thanks for the information

kachenXDEXE

and when i click the button it isnt work as i set WHY is my code is wrong or this website is bad please tell me

kachenXDEXE

Please tell me is my code wrong or this website is bad :(