按下按钮时,命令不会运行

时间:2017-11-05 08:00:26

标签: python button tkinter

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

lambda按钮command中不需要setAlarm

command = setAlarm不得调用该函数(删除括号)。

该按钮不需要命名,并且肯定不会影响setAlarm功能。如果你想给它命名,并指定它,你不应该把它打包在同一条线上; pack方法返回None

您在grid

中的同一位置存放了所有5个帧
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()