0

Please note that this is written in python 3

I am using Tkinter and am trying to call the foo-function by pressing the button in the tk-window and get "Hello World!" printed, what am I doing wrong?

from tkinter import *
window1 = Tk()

class WidgetCreate(object):

    def __init__(self, widget_type, window_num, text_str, fun, numr, numc):
        self.obj = Button(window_num, text=text_str, command=lambda: fun)
        self.obj.grid(row=numr, column=numc)

def foo():
    print("Hello World!")       

but1 = WidgetCreate("Button", window1, "This Button 1", foo, 1, 1)

window1.mainloop()

The button is visible in the to-window however when pressed nothing happens :(

3
  • If an answer solves your problem, it would be nice if you mark it as accepted. Commented Jun 30, 2014 at 16:18
  • Sorry for the delay, There! Done! :) Commented Jun 30, 2014 at 17:02
  • The delay is no problem. Thanks, I commented only because you could have forgotten / not found it as new user. :) Commented Jun 30, 2014 at 17:10

1 Answer 1

2

You miss the parenthesis in your command argument to Button. So your lambda function doesn't call the function you want. It has to be:

self.obj = Button(window_num, text=text_str, command=lambda: fun())

Or even simpler you do it without the lambda function and give fun directly as argument:

self.obj = Button(window_num, text=text_str, command=fun)
Sign up to request clarification or add additional context in comments.

3 Comments

That little error took me 2 whole hours to notice. Thank you!
It's even better if you use the second way, because the lambda thing is not necessary.
Typically you'll only need a lambda if you have to pass arguments to a function. If you had to tell foo what to print, you'd have to do command=lambda: fun("Hello, world!") but if you can just call the function then there's no reason to wrap it inside another function :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.