【问题标题】:When button is pressed, the command doesn't run按下按钮时,命令不运行
【发布时间】:2017-11-05 08:00:25
【问题描述】:
def setAlarm():
    X = 5+5
    frame2.tkraise()
    print X

app = Tk()

hour = IntVar()
minute = IntVar()
period = StringVar()
hour.set(None)
minute.set(None)
period.set(None)
frame1 = Frame(app) #main frame
frame2 = Frame(app) #hour frame
frame3 = Frame(app) #minutes frame
frame4 = Frame(app) #period frame
frame5 = Frame(app) #something frame
    for frame in (frame1, frame2, frame3, frame4, frame5):
        frame.grid(row=10, column=10, sticky='news') # sets frame layout

setAlarm = Button(frame1, text = "Set Alarm", command = lambda:setAlarm()).pack()

我在第 1 帧中有一个按钮,按下它时应该显示第 2 帧。但是,当我单击该按钮时,没有任何反应。不应该调用 setAlarm() 将 frame2 带到前面吗?相反,我得到了这个错误。

File "C:/Users/Jeffrey/PycharmProjects/untitled/Graphical User 
Interface.py", line 60, in <lambda>
    setAlarm = Button(frame1, text = "Set Alarm", command = 
lambda:setAlarm()).pack()
TypeError: 'NoneType' object is not callable

【问题讨论】:

    标签: python button tkinter


    【解决方案1】:

    您定义了 setAlarm 函数,但在此行执行后立即覆盖它

    setAlarm = Button(frame1, text = "Set Alarm", command = lambda:setAlarm()).pack()

    使用Nonepack() 返回None)。

    您不需要重新分配给setAlarm

    事实上,您甚至不需要lambda。您已经定义了setAlarm,所以您不妨直接使用它:

    Button(frame1, text="Set Alarm", command=setAlarm).pack()


    进一步说明

    你的代码相当于这样:

    def foo():
        print('foo')
    
    bar = lambda: foo()
    
    foo = None
    
    bar()
    

    哪个结果有相同的错误:

    bar = lambda: foo()
    TypeError: 'NoneType' object is not callable
    

    bar() 执行时,foo 已经是None

    【讨论】:

      【解决方案2】:

      对于setAlarm 按钮,您不需要在command 中使用lambda

      command = setAlarm 不能调用函数(去掉括号)。

      该按钮不需要命名,当然也不会影响setAlarm 函数。如果要命名、赋值,不要打包在同一行; pack 方法返回 None

      您将所有 5 个帧都存放在 grid 中的同一位置

      from tkinter import *
      
      def setAlarm2():
          X = 5 + 5
          frame2.tkraise()
          print(X)
      
      app = Tk()
      
      hour = IntVar()
      minute = IntVar()
      period = StringVar()
      hour.set(None)
      minute.set(None)
      period.set(None)
      frame1 = Frame(app) #main frame
      frame2 = Frame(app) #hour frame
      frame3 = Frame(app) #minutes frame
      frame4 = Frame(app) #period frame
      frame5 = Frame(app) #something frame
      
      frames = (frame1, frame2, frame3, frame4, frame5)
      
      for row, frame in enumerate(frames):
          frame.grid(row=row, column=0, sticky='news') # sets frame layout
      
      Button(frame1, text = "Set Alarm", command = setAlarm2).pack()
      
      app.mainloop()
      

      【讨论】:

        猜你喜欢
        • 2019-05-10
        • 2017-12-23
        • 1970-01-01
        • 2012-10-07
        • 1970-01-01
        • 2016-07-10
        • 2012-04-10
        • 2012-12-01
        • 1970-01-01
        相关资源
        最近更新 更多