【问题标题】:Python3: function call from pressing tkinter.buttonPython3:按 tkinter.button 调用函数
【发布时间】:2014-08-21 01:50:17
【问题描述】:

请注意这是用python 3编写的

我正在使用 Tkinter 并试图通过按下 tk 窗口中的按钮来调用 foo 函数并获得“Hello World!”打印,我做错了什么?

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()

该按钮在 to-window 中可见,但是当按下时没有任何反应:(

【问题讨论】:

  • 如果一个答案解决了你的问题,如果你mark it as accepted会很好。
  • 抱歉耽搁了,有!完毕! :)
  • 延迟没问题。谢谢,我评论只是因为你可能忘记/没有找到它作为新用户。 :)

标签: python python-3.x tkinter


【解决方案1】:

您错过了 Buttoncommand 参数中的括号。所以你的 lambda 函数不会调用你想要的函数。它必须是:

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

或者甚至更简单,您可以不使用 lambda 函数并直接将 fun 作为参数:

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

【讨论】:

  • 这个小错误花了我整整 2 个小时才注意到。谢谢!
  • 如果使用第二种方式就更好了,因为lambda这个东西不是必须的。
  • 如果您必须将参数传递给函数,通常只需要lambda。如果你必须告诉foo 要打印什么,你必须做command=lambda: fun("Hello, world!") 但如果你可以调用该函数,那么没有理由将它包装在另一个函数中:)
猜你喜欢
  • 2016-10-07
  • 1970-01-01
  • 2017-12-08
  • 2016-05-25
  • 1970-01-01
  • 2013-10-12
  • 2017-10-10
  • 1970-01-01
  • 2012-01-10
相关资源
最近更新 更多