0

If I run this , it will run the command without pressing the button. And I know I can change variable a to "hi" on the second line, but I cant on another piece of code that I am working on (I made this one to be a lot simpler and easier to explain(not because you wouldn't understand))

I have tried changing what is in between the brackets on the 4th line, that didn't help.

from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
def helloCallBack(a):
    msg = messagebox.showinfo( "Hello Python", a)

B = Button(top, text = "Hello", command = helloCallBack("hi"))
B.place(x = 50,y = 50)
top.mainloop()

I was hoping, that as soon as the button was pressed, not before, the message box would appear and show "Python hi".

wondercoll
  • 339
  • 1
  • 4
  • 15

1 Answers1

1

Use a lambda to pass the entry data to the command function:

from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
def helloCallBack(a):
    msg = messagebox.showinfo( "Hello Python", a)
B = Button(top, text = "Hello", command = lambda: helloCallBack('hi'))
B.place(x = 50,y = 50)
B.pack()
top.mainloop()
ncica
  • 7,015
  • 1
  • 15
  • 37
  • thanks, i have already found a different (worse) way of doing it, but it makes more sense in my head so i will stick with it, if you want to know how i did it comment me back, but still thanks a lot :D – wondercoll May 28 '19 at 14:41
  • I will appreciate it. it is always good to know more solutions, tnx:) @wondercoll – ncica May 28 '19 at 15:06
  • 1
    it would be hard to change the code, so i will just tell you, if i define a before the button it then understands what a is and i do not need it when i call the command, but it only works if i only want to use that def once. As i said, much worse, but it makes sence. – wondercoll May 30 '19 at 15:09
  • nice, thank you :) @wondercoll – ncica May 30 '19 at 15:21